LeetCode 题解工作台
字符频次唯一的最小删除次数
如果字符串 s 中 不存在 两个不同字符 频次 相同的情况,就称 s 是 优质字符串 。 给你一个字符串 s ,返回使 s 成为 优质字符串 需要删除的 最小 字符数。 字符串中字符的 频次 是该字符在字符串中的出现次数。例如,在字符串 "aab" 中, 'a' 的频次是 2 ,而 'b' 的频次是…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们先用一个长度为 的数组 统计字符串 中每个字母出现的次数。 然后我们对数组 进行倒序排序。定义一个变量 记录当前字母的出现次数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
如果字符串 s 中 不存在 两个不同字符 频次 相同的情况,就称 s 是 优质字符串 。
给你一个字符串 s,返回使 s 成为 优质字符串 需要删除的 最小 字符数。
字符串中字符的 频次 是该字符在字符串中的出现次数。例如,在字符串 "aab" 中,'a' 的频次是 2,而 'b' 的频次是 1 。
示例 1:
输入:s = "aab"
输出:0
解释:s 已经是优质字符串。
示例 2:
输入:s = "aaabbbcc" 输出:2 解释:可以删除两个 'b' , 得到优质字符串 "aaabcc" 。 另一种方式是删除一个 'b' 和一个 'c' ,得到优质字符串 "aaabbc" 。
示例 3:
输入:s = "ceabaacb" 输出:2 解释:可以删除两个 'c' 得到优质字符串 "eabaab" 。 注意,只需要关注结果字符串中仍然存在的字符。(即,频次为 0 的字符会忽略不计。)
提示:
1 <= s.length <= 105s仅含小写英文字母
解题思路
方法一:数组 + 排序
我们先用一个长度为 的数组 统计字符串 中每个字母出现的次数。
然后我们对数组 进行倒序排序。定义一个变量 记录当前字母的出现次数。
接下来,遍历数组 每个元素 ,如果当前 等于 ,我们直接将答案加上 ;否则,如果 ,我们将答案加上 ,并且将 减去 ,否则,我们直接将 更新为 。然后继续遍历下个元素。
遍历结束,返回答案即可。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度,而 为字母集的大小。本题中 。
class Solution:
def minDeletions(self, s: str) -> int:
cnt = Counter(s)
ans, pre = 0, inf
for v in sorted(cnt.values(), reverse=True):
if pre == 0:
ans += v
elif v >= pre:
ans += v - pre + 1
pre -= 1
else:
pre = v
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) to count frequencies plus O(k log k) if sorting frequencies is used, where k is the number of distinct characters; space complexity is O(k) for the frequency map and O(k) for the set of used frequencies. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect a linear scan over the frequency counts with conflict resolution.
- question_mark
Watch for edge cases where multiple characters share the same frequency.
- question_mark
Check that zero-frequency characters are ignored when validating uniqueness.
常见陷阱
外企场景- error
Failing to decrement frequencies correctly when duplicates exist, leading to overcounted deletions.
- error
Not ignoring characters reduced to zero frequency, which can falsely appear as conflicts.
- error
Assuming characters must be deleted in input order rather than using a frequency-based greedy reduction.
进阶变体
外企场景- arrow_right_alt
Find the minimum insertions to make all character frequencies unique instead of deletions.
- arrow_right_alt
Apply the same frequency uniqueness constraint to subsets of the string or sliding windows.
- arrow_right_alt
Modify the problem to allow only specific characters to be deleted, testing selective greedy application.