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 makeevery string in _wordsequal using
any number of operations,andfalseotherwise.
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 returntrue.
classSolution {
public:bool makeEqual(vector<string>& words) {
vector<int> cnt(26, 0);
for (auto& w : words)
for (char c : w) cnt[c -'a']++;
int n = words.size();
for (int x : cnt) if (x % n) return false;
return true;
}
};
classSolution {
publicbooleanmakeEqual(String[] words) {
int[] cnt =newint[26];
for (String w : words)
for (char c : w.toCharArray()) cnt[c -'a']++;
int n = words.length;
for (int x : cnt) if (x % n != 0) returnfalse;
returntrue;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funmakeEqual(words: Array<String>): Boolean {
val cnt = IntArray(26)
for (w in words) for (c in w) cnt[c - 'a']++val n = words.size
for (x in cnt) if (x % n !=0) returnfalsereturntrue }
}
1
2
3
4
5
6
7
8
classSolution:
defmakeEqual(self, words: list[str]) -> bool:
cnt = [0] *26for w in words:
for c in w:
cnt[ord(c) - ord('a')] +=1 n = len(words)
return all(x % n ==0for x in cnt)
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnmake_equal(words: Vec<String>) -> bool {
letmut cnt = [0; 26];
for w in words.iter() {
for c in w.chars() {
cnt[(c asu8-b'a') asusize] +=1;
}
}
let n = words.len();
cnt.iter().all(|&x| x % n ==0)
}
}
1
2
3
4
5
6
7
8
classSolution {
makeEqual(words: string[]):boolean {
constcnt= Array(26).fill(0);
for (constwofwords) for (constcofw) cnt[c.charCodeAt(0) -97]++;
constn=words.length;
returncnt.every(x=>x%n===0);
}
}