LeetCode 1897. Redistribute Characters to Make All Strings Equal【字符串/哈希表】简单
发布日期:2021-07-01 03:02:26 浏览次数:2 分类:技术文章

本文共 1435 字,大约阅读时间需要 4 分钟。

You are given an array of strings words (0-indexed).

In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].

Return true if you can make every string in words equal using any number of operations, and false otherwise.

Example 1:

Input: words = ["abc","aabc","bc"]Output: trueExplanation: Move the first 'a' in words[1] to the front of words[2],to make words[1] = "abc" and words[2] = "abc".All the strings are now equal to "abc", so return true.

Example 2:

Input: words = ["ab","a"]Output: falseExplanation: It is impossible to make all the strings equal using the operation.

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of lowercase English letters.

题意:给你一个字符串数组 words(下标 从 0 开始 计数)。在一步操作中,需先选出两个 不同 下标 ij,其中 words[i] 是一个非空字符串,接着将 words[i] 中的 任一 字符移动到 words[j] 中的 任一 位置上。

如果执行任意步操作可以使 words 中的每个字符串都相等,返回 true ;否则,返回 false


解法 哈希表

检查每种字符是否可以平均分到所有字符串:

class Solution {
public: bool makeEqual(vector
& words) {
int cnt[26] = {
0}, n = words.size(); for (int i = 0; i < n; ++i) for (int j = 0, m = words[i].size(); j < m; ++j) ++cnt[words[i][j] - 'a']; for (int i = 0; i < 26; ++i) if (cnt[i] % n != 0) return false; return true; }};

运行效率如下:

执行用时:8 ms, 在所有 C++ 提交中击败了99.56% 的用户内存消耗:11.2 MB, 在所有 C++ 提交中击败了89.99% 的用户

转载地址:https://memcpy0.blog.csdn.net/article/details/117917135 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode 1893. Check if All the Integers in a Range Are Covered【数组/差分】简单
下一篇:LeetCode 374. Guess Number Higher or Lower【二分】简单

发表评论

最新留言

很好
[***.229.124.182]2024年04月19日 12时34分14秒