原文链接: https://leetcode-cn.com/problems/redistribute-characters-to-make-all-strings-equal
英文原文
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: true Explanation: Move the first 'a' inwords[1] to the front of words[2], to makewords[1]= "abc" and words[2] = "abc". All the strings are now equal to "abc", so returntrue.
Example 2:
Input: words = ["ab","a"] Output: false Explanation: It is impossible to make all the strings equal using the operation.
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]consists of lowercase English letters.
中文题目
给你一个字符串数组 words(下标 从 0 开始 计数)。
在一步操作中,需先选出两个 不同 下标 i 和 j,其中 words[i] 是一个非空字符串,接着将 words[i] 中的 任一 字符移动到 words[j] 中的 任一 位置上。
如果执行任意步操作可以使 words 中的每个字符串都相等,返回 true ;否则,返回 false 。
示例 1:
输入:words = ["abc","aabc","bc"] 输出:true 解释:将words[1] 中的第一个'a' 移动到words[2] 的最前面。 使words[1]= "abc" 且 words[2] = "abc" 。 所有字符串都等于 "abc" ,所以返回true。
示例 2:
输入:words = ["ab","a"] 输出:false 解释:执行操作无法使所有字符串都相等。
提示:
1 <= words.length <= 1001 <= words[i].length <= 100words[i]由小写英文字母组成
通过代码
高赞题解
题解
题目中有说到,在经过无数次移动之后所有字符串都相等,意思也就是说:这个字符串的每一个字符的数量也是相等的,我们统计这个字符串数组里每个字符的数量,这个字符的数量应该是words数组长度len的倍数,因此可以得出:一个字符的总数对len取余,结果不为0则返回false,如果所有字符对len取余结果都为0,则返回true
代码实现如下
代码
class Solution {
public boolean makeEqual(String[] words) {
int len = words.length;
int[] charCount = new int[129];
for (String word : words) {
for (char c : word.toCharArray()) {
charCount[c]++;
}
}
for (int i : charCount) {
if ( i % len != 0)
return false;
}
return true;
}
}
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 6735 | 12566 | 53.6% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|