LeetCode 题解工作台

检查是否所有字符出现次数相同

给你一个字符串 s ,如果 s 是一个 好 字符串,请你返回 true ,否则请返回 false 。 如果 s 中出现过的 所有 字符的出现次数 相同 ,那么我们称字符串 s 是 好 字符串。 示例 1: 输入: s = "abacbc" 输出: true 解释: s 中出现过的字符为 'a','b…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

我们用一个哈希表或者一个长度为 的数组 记录字符串 中每个字符出现的次数。 接下来遍历 中的每个值,判断所有非零值是否相等即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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 <= 1000
  • s 只包含小写英文字母。
lightbulb

解题思路

方法一:计数

我们用一个哈希表或者一个长度为 2626 的数组 cnt\textit{cnt} 记录字符串 ss 中每个字符出现的次数。

接下来遍历 cnt\textit{cnt} 中的每个值,判断所有非零值是否相等即可。

时间复杂度 O(n)O(n),空间复杂度 O(Σ)O(|\Sigma|)。其中 nn 是字符串 ss 的长度;而 Σ\Sigma 是字符集大小,本题中字符集为小写英文字母,因此 Σ=26|\Sigma|=26

1
2
3
4
class Solution:
    def areOccurrencesEqual(self, s: str) -> bool:
        return len(set(Counter(s).values())) == 1
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

检查是否所有字符出现次数相同题解:哈希·表·结合·string | LeetCode #1941 简单