「每日LeetCode」2021年7月10日

本文最后更新于:2023年3月19日 晚上

Lt1897. 重新分配字符使所有字符串都相等

1897. 重新分配字符使所有字符串都相等

给你一个字符串数组 words(下标 从 0 开始 计数)。
在一步操作中,需先选出两个 不同 下标 ij,其中 words[i] 是一个非空字符串,接着将 words[i] 中的 任一 字符移动到 words[j] 中的 任一 位置上。
如果执行任意步操作可以使 words 中的每个字符串都相等,返回 true;否则,返回 _false
 示例 1:

1
2
3
4
5
输入:words = ["abc","aabc","bc"]
输出:true
解释:将 words[1] 中的第一个 'a' 移动到 words[2] 的最前面。
使 words[1] = "abc"words[2] = "abc"
所有字符串都等于 "abc" ,所以返回 true

示例 2:

1
2
3
输入:words = ["ab","a"]
输出:false
解释:执行操作无法使所有字符串都相等。

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] 由小写英文字母组成

思路

用 map 记录所有出现的字符数量,判断每个字符数量是不是都是数组长度的整数倍即可。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {string[]} words
* @return {boolean}
*/
var makeEqual = function (words) {
const map = {};
const count = (word) => {
for (const char of word) {
if (map[char]) map[char]++;
else map[char] = 1;
}
};
for (const word of words) count(word);
return Object.values(map).every((e) => e % words.length === 0);
};