LeetCode 题解工作台
检查是否所有字符出现次数相同
给你一个字符串 s ,如果 s 是一个 好 字符串,请你返回 true ,否则请返回 false 。 如果 s 中出现过的 所有 字符的出现次数 相同 ,那么我们称字符串 s 是 好 字符串。 示例 1: 输入: s = "abacbc" 输出: true 解释: s 中出现过的字符为 'a','b…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们用一个哈希表或者一个长度为 的数组 记录字符串 中每个字符出现的次数。 接下来遍历 中的每个值,判断所有非零值是否相等即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个字符串 s ,如果 s 是一个 好 字符串,请你返回 true ,否则请返回 false 。
如果 s 中出现过的 所有 字符的出现次数 相同 ,那么我们称字符串 s 是 好 字符串。
示例 1:
输入:s = "abacbc" 输出:true 解释:s 中出现过的字符为 'a','b' 和 'c' 。s 中所有字符均出现 2 次。
示例 2:
输入:s = "aaabb" 输出:false 解释:s 中出现过的字符为 'a' 和 'b' 。 'a' 出现了 3 次,'b' 出现了 2 次,两者出现次数不同。
提示:
1 <= s.length <= 1000s只包含小写英文字母。
解题思路
方法一:计数
我们用一个哈希表或者一个长度为 的数组 记录字符串 中每个字符出现的次数。
接下来遍历 中的每个值,判断所有非零值是否相等即可。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度;而 是字符集大小,本题中字符集为小写英文字母,因此 。
class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
return len(set(Counter(s).values())) == 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate should efficiently build and check the frequency table.
- question_mark
The candidate should consider edge cases like strings with only one type of character or strings with a large number of unique characters.
- question_mark
The candidate should demonstrate an understanding of optimizing with early exits.
常见陷阱
外企场景- error
Forgetting to check the frequency consistency across all characters.
- error
Using inefficient data structures that lead to unnecessary computation or memory usage.
- error
Not handling strings with varying numbers of unique characters correctly.
进阶变体
外企场景- arrow_right_alt
Modify the problem to include case-insensitive comparisons.
- arrow_right_alt
Allow the string to contain non-English characters.
- arrow_right_alt
Optimize the solution to handle very large strings with more efficient space usage.