LeetCode 1897: Redistribute Characters to Make All Strings Equal (Counting)
English
Count each letter across all words. If every letter count is divisible by n (number of words), then we can redistribute characters so each string gets exactly the same multiset of letters. Otherwise it is impossible.
class Solution {
public boolean makeEqual(String[] words) {
int[] cnt = new int[26];
for (String w : words) {
for (int i = 0; i < w.length(); i++) {
cnt[w.charAt(i) - 'a']++;
}
}
int n = words.length;
for (int c : cnt) {
if (c % n != 0) return false;
}
return true;
}
}func makeEqual(words []string) bool {
cnt := make([]int, 26)
for _, w := range words {
for i := 0; i < len(w); i++ {
cnt[w[i]-'a']++
}
}
n := len(words)
for _, c := range cnt {
if c%n != 0 {
return false
}
}
return true
}class Solution {
public:
bool makeEqual(vector<string>& words) {
vector<int> cnt(26, 0);
for (auto& w : words) {
for (char ch : w) cnt[ch - 'a']++;
}
int n = (int)words.size();
for (int c : cnt) {
if (c % n != 0) return false;
}
return true;
}
};class Solution:
def makeEqual(self, words: List[str]) -> bool:
cnt = [0] * 26
for w in words:
for ch in w:
cnt[ord(ch) - ord('a')] += 1
n = len(words)
return all(c % n == 0 for c in cnt)var makeEqual = function(words) {
const cnt = new Array(26).fill(0);
for (const w of words) {
for (const ch of w) {
cnt[ch.charCodeAt(0) - 97]++;
}
}
const n = words.length;
for (const c of cnt) {
if (c % n !== 0) return false;
}
return true;
};中文
统计所有单词中每个字母的总出现次数。若每个字母总数都能被 n(单词数量)整除,就能把字符重新分配到每个字符串,使它们字符多重集完全相同;只要有一个字母不满足整除,就无法做到。
class Solution {
public boolean makeEqual(String[] words) {
int[] cnt = new int[26];
for (String w : words) {
for (int i = 0; i < w.length(); i++) {
cnt[w.charAt(i) - 'a']++;
}
}
int n = words.length;
for (int c : cnt) {
if (c % n != 0) return false;
}
return true;
}
}func makeEqual(words []string) bool {
cnt := make([]int, 26)
for _, w := range words {
for i := 0; i < len(w); i++ {
cnt[w[i]-'a']++
}
}
n := len(words)
for _, c := range cnt {
if c%n != 0 {
return false
}
}
return true
}class Solution {
public:
bool makeEqual(vector<string>& words) {
vector<int> cnt(26, 0);
for (auto& w : words) {
for (char ch : w) cnt[ch - 'a']++;
}
int n = (int)words.size();
for (int c : cnt) {
if (c % n != 0) return false;
}
return true;
}
};class Solution:
def makeEqual(self, words: List[str]) -> bool:
cnt = [0] * 26
for w in words:
for ch in w:
cnt[ord(ch) - ord('a')] += 1
n = len(words)
return all(c % n == 0 for c in cnt)var makeEqual = function(words) {
const cnt = new Array(26).fill(0);
for (const w of words) {
for (const ch of w) {
cnt[ch.charCodeAt(0) - 97]++;
}
}
const n = words.length;
for (const c of cnt) {
if (c % n !== 0) return false;
}
return true;
};