LeetCode 题解工作台

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

给你一个字符串数组 words (下标 从 0 开始 计数)。 在一步操作中,需先选出两个 不同 下标 i 和 j ,其中 words[i] 是一个非空字符串,接着将 words[i] 中的 任一 字符移动到 words[j] 中的 任一 位置上。 如果执行任意步操作可以使 words 中的每个字符…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

根据题目描述,只要每个字符的出现次数能被字符串数组的长度整除,就可以通过移动字符使所有字符串相等。 因此,我们用哈希表或者一个长度为 的整数数组 统计每个字符出现的次数,最后判断是否每个字符的出现次数能被字符串数组的长度整除即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串数组 words(下标 从 0 开始 计数)。

在一步操作中,需先选出两个 不同 下标 ij,其中 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 <= 100
  • 1 <= words[i].length <= 100
  • words[i] 由小写英文字母组成
lightbulb

解题思路

方法一:计数

根据题目描述,只要每个字符的出现次数能被字符串数组的长度整除,就可以通过移动字符使所有字符串相等。

因此,我们用哈希表或者一个长度为 2626 的整数数组 cnt\textit{cnt} 统计每个字符出现的次数,最后判断是否每个字符的出现次数能被字符串数组的长度整除即可。

时间复杂度 O(L)O(L),空间复杂度 O(Σ)O(|\Sigma|)。其中 LL 为数组 words\textit{words} 中所有字符串的长度之和,而 Σ\Sigma 为字符集,这里为小写字母集合,所以 Σ=26|\Sigma|=26

1
2
3
4
5
6
7
8
9
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())
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

重新分配字符使所有字符串都相等题解:哈希·表·结合·string | LeetCode #1897 简单