LeetCode 题解工作台

删除字符使频率相同

给你一个下标从 0 开始的字符串 word ,字符串只包含小写英文字母。你需要选择 一个 下标并 删除 下标处的字符,使得 word 中剩余每个字母出现 频率 相同。 如果删除一个字母后, word 中剩余所有字母的出现频率都相同,那么返回 true ,否则返回 false 。 注意: 字母 x 的…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

我们先用哈希表或者一个长度为 的数组 统计字符串中每个字母出现的次数。 接下来,枚举 个字母,如果字母 在字符串中出现过,我们将其出现次数减一,然后判断剩余的字母出现次数是否相同。如果相同,返回 `true`,否则将 的出现次数加一,继续枚举下一个字母。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的字符串 word ,字符串只包含小写英文字母。你需要选择 一个 下标并 删除 下标处的字符,使得 word 中剩余每个字母出现 频率 相同。

如果删除一个字母后,word 中剩余所有字母的出现频率都相同,那么返回 true ,否则返回 false 。

注意:

  • 字母 x 的 频率 是这个字母在字符串中出现的次数。
  • 必须 恰好删除一个字母,不能一个字母都不删除。

 

示例 1:

输入:word = "abcc"
输出:true
解释:选择下标 3 并删除该字母:word 变成 "abc" 且每个字母出现频率都为 1 。

示例 2:

输入:word = "aazz"
输出:false
解释:我们必须删除一个字母,所以要么 "a" 的频率变为 1 且 "z" 的频率为 2 ,要么两个字母频率反过来。所以不可能让剩余所有字母出现频率相同。

 

提示:

  • 2 <= word.length <= 100
  • word 只包含小写英文字母。
lightbulb

解题思路

方法一:计数 + 枚举

我们先用哈希表或者一个长度为 2626 的数组 cntcnt 统计字符串中每个字母出现的次数。

接下来,枚举 2626 个字母,如果字母 cc 在字符串中出现过,我们将其出现次数减一,然后判断剩余的字母出现次数是否相同。如果相同,返回 true,否则将 cc 的出现次数加一,继续枚举下一个字母。

枚举结束,说明无法通过删除一个字母使得剩余字母出现次数相同,返回 false

时间复杂度 O(n+C2)O(n + C^2),空间复杂度 O(C)O(C),其中 nn 为字符串 wordword 的长度,而 CC 为字符集的大小,本题中 C=26C = 26

1
2
3
4
5
6
7
8
9
10
class Solution:
    def equalFrequency(self, word: str) -> bool:
        cnt = Counter(word)
        for c in cnt.keys():
            cnt[c] -= 1
            if len(set(v for v in cnt.values() if v)) == 1:
                return True
            cnt[c] += 1
        return False
speed

复杂度分析

指标
时间complexity is O(N) to count letters and O(U) to check possible removals, where N is string length and U is number of unique letters (max 26). Space complexity is O(U) for the hash table storing frequencies.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if the candidate correctly uses a hash table for frequency counting.

  • question_mark

    Look for handling of single-character edge cases and uniform strings.

  • question_mark

    Expect the candidate to simulate removal efficiently rather than reconstructing the string each time.

warning

常见陷阱

外企场景
  • error

    Failing to consider letters that appear only once can lead to incorrect results.

  • error

    Not updating frequency counts correctly during simulated removal can cause logic errors.

  • error

    Overcomplicating the solution instead of leveraging hash table counting pattern.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Instead of removing one letter, allow removing up to K letters to equalize frequency.

  • arrow_right_alt

    Check if adding a single letter can make all frequencies equal.

  • arrow_right_alt

    Determine the minimum number of removals to achieve equal frequency.

help

常见问题

外企场景

删除字符使频率相同题解:哈希·表·结合·string | LeetCode #2423 简单