LeetCode 题解工作台
重新分配字符使所有字符串都相等
给你一个字符串数组 words (下标 从 0 开始 计数)。 在一步操作中,需先选出两个 不同 下标 i 和 j ,其中 words[i] 是一个非空字符串,接着将 words[i] 中的 任一 字符移动到 words[j] 中的 任一 位置上。 如果执行任意步操作可以使 words 中的每个字符…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
根据题目描述,只要每个字符的出现次数能被字符串数组的长度整除,就可以通过移动字符使所有字符串相等。 因此,我们用哈希表或者一个长度为 的整数数组 统计每个字符出现的次数,最后判断是否每个字符的出现次数能被字符串数组的长度整除即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个字符串数组 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]由小写英文字母组成
解题思路
方法一:计数
根据题目描述,只要每个字符的出现次数能被字符串数组的长度整除,就可以通过移动字符使所有字符串相等。
因此,我们用哈希表或者一个长度为 的整数数组 统计每个字符出现的次数,最后判断是否每个字符的出现次数能被字符串数组的长度整除即可。
时间复杂度 ,空间复杂度 。其中 为数组 中所有字符串的长度之和,而 为字符集,这里为小写字母集合,所以 。
class Solution:
def makeEqual(self, words: List[str]) -> bool:
cnt = Counter()
for w in words:
for c in w:
cnt[c] += 1
n = len(words)
return all(v % n == 0 for v in cnt.values())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n * k) where n is the number of strings and k is the average string length, due to counting each character. Space complexity is O(1) because only 26 lowercase letters are counted regardless of input size. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Notice that the order of characters in strings does not matter, only total counts matter.
- question_mark
Check for divisibility by the number of strings as a quick feasibility check.
- question_mark
Consider edge cases with strings of different lengths or empty strings.
常见陷阱
外企场景- error
Ignoring the character frequency divisibility check and trying to simulate movements directly.
- error
Assuming character positions matter rather than just counts.
- error
Overlooking edge cases where a character total count is not divisible by the number of strings.
进阶变体
外企场景- arrow_right_alt
Modify the problem to include uppercase letters or digits, changing the hash table size.
- arrow_right_alt
Limit the number of allowed moves and determine if equality is still achievable.
- arrow_right_alt
Allow only adjacent character swaps and analyze feasibility differently.