LeetCode 题解工作台
成为 K 特殊字符串需要删除的最少字符数
给你一个字符串 word 和一个整数 k 。 如果 |freq(word[i]) - freq(word[j])| 对于字符串中所有下标 i 和 j 都成立,则认为 word 是 k 特殊字符串 。 此处, freq(x) 表示字符 x 在 word 中的 出现频率 ,而 |y| 表示 y 的绝对值…
5
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们可以先统计字符串中每个字符的出现次数,将所有次数放入数组 中,由于题目中字符串只包含小写字母,所以数组 的长度不会超过 。 接下来,我们可以枚举在 的范围内枚举 特殊字符串中的字符最小频率 ,然后用一个函数 来计算将所有字符的频率调整为 的最小删除次数,最后取所有 的最小值即为答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个字符串 word 和一个整数 k。
如果 |freq(word[i]) - freq(word[j])| <= k 对于字符串中所有下标 i 和 j 都成立,则认为 word 是 k 特殊字符串。
此处,freq(x) 表示字符 x 在 word 中的出现频率,而 |y| 表示 y 的绝对值。
返回使 word 成为 k 特殊字符串 需要删除的字符的最小数量。
示例 1:
输入:word = "aabcaba", k = 0
输出:3
解释:可以删除 2 个 "a" 和 1 个 "c" 使 word 成为 0 特殊字符串。word 变为 "baba",此时 freq('a') == freq('b') == 2。
示例 2:
输入:word = "dabdcbdcdcd", k = 2
输出:2
解释:可以删除 1 个 "a" 和 1 个 "d" 使 word 成为 2 特殊字符串。word 变为 "bdcbdcdcd",此时 freq('b') == 2,freq('c') == 3,freq('d') == 4。
示例 3:
输入:word = "aaabaaa", k = 2
输出:1
解释:可以删除 1 个 "b" 使 word 成为 2特殊字符串。因此,word 变为 "aaaaaa",此时每个字母的频率都是 6。
提示:
1 <= word.length <= 1050 <= k <= 105word仅由小写英文字母组成。
解题思路
方法一:计数 + 枚举
我们可以先统计字符串中每个字符的出现次数,将所有次数放入数组 中,由于题目中字符串只包含小写字母,所以数组 的长度不会超过 。
接下来,我们可以枚举在 的范围内枚举 特殊字符串中的字符最小频率 ,然后用一个函数 来计算将所有字符的频率调整为 的最小删除次数,最后取所有 的最小值即为答案。
函数 的计算方法如下:
遍历数组 中的每个元素 ,如果 ,则说明我们需要将出现次数为 的字符全部删除,删除次数为 ;如果 ,则说明我们需要将出现次数为 的字符全部调整为 ,删除次数为 。累加所有删除次数即为 的值。
时间复杂度 ,空间复杂度 。其中 为字符串长度;而 为字符集大小,本题中 。
class Solution:
def minimumDeletions(self, word: str, k: int) -> int:
def f(v: int) -> int:
ans = 0
for x in nums:
if x < v:
ans += x
elif x > v + k:
ans += x - v - k
return ans
nums = Counter(word).values()
return min(f(v) for v in range(len(word) + 1))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n + C^2) |
| 空间 | O(C) |
面试官常问的追问
外企场景- question_mark
Understand frequency counting and its importance for this problem.
- question_mark
Demonstrate ability to apply a greedy strategy to optimize deletions.
- question_mark
Check for a valid approach by maintaining the invariant while making deletions.
常见陷阱
外企场景- error
Not using a hash table for efficient frequency counting can lead to slower solutions.
- error
Forgetting to sort the frequencies might result in suboptimal deletions.
- error
Incorrectly applying the greedy approach might lead to an invalid final string.
进阶变体
外企场景- arrow_right_alt
Instead of minimizing deletions, the problem could be framed as maximizing the number of characters that remain in the string.
- arrow_right_alt
The problem could involve different limits on k or the size of the string, testing the solution's scalability.
- arrow_right_alt
Instead of just deletions, the problem could also involve transforming characters to meet the k-special condition.