LeetCode 题解工作台
使字符频率相等的最少操作次数
给你一个字符串 s 。 如果字符串 t 中的字符出现次数相等,那么我们称 t 为 好的 。 你可以执行以下操作 任意次 : 从 s 中删除一个字符。 往 s 中添加一个字符。 将 s 中一个字母变成字母表中下一个字母。 注意 ,第三个操作不能将 'z' 变为 'a' 。 请你返回将 s 变 好 的 …
5
题型
0
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个字符串 s 。
如果字符串 t 中的字符出现次数相等,那么我们称 t 为 好的 。
你可以执行以下操作 任意次 :
- 从
s中删除一个字符。 - 往
s中添加一个字符。 - 将
s中一个字母变成字母表中下一个字母。
注意 ,第三个操作不能将 'z' 变为 'a' 。
请你返回将 s 变 好 的 最少 操作次数。
示例 1:
输入:s = "acab"
输出:1
解释:
删掉一个字符 'a' ,s 变为好的。
示例 2:
输入:s = "wddw"
输出:0
解释:
s 一开始就是好的,所以不需要执行任何操作。
示例 3:
输入:s = "aaabc"
输出:2
解释:
通过以下操作,将 s 变好:
- 将一个
'a'变为'b'。 - 往
s中插入一个'c'。
提示:
1 <= s.length <= 2 * 104s只包含小写英文字母。
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the number of unique character frequencies and DP state transitions, roughly O(n log n) for counting and sorting plus frequency adjustment iterations. Space complexity is dominated by hash table storage and DP table, typically O(n) for character counts. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for correct use of hash table to tally character frequencies.
- question_mark
Check if candidate properly applies dynamic programming for state transitions between frequency reductions.
- question_mark
Assess awareness of trade-offs between deleting excess characters versus leaving frequencies uneven.
常见陷阱
外企场景- error
Failing to account for multiple characters sharing the same frequency, leading to incorrect minimal deletions.
- error
Overcomplicating the DP by considering unnecessary permutations of character deletions.
- error
Neglecting edge cases where all characters already have equal frequency, resulting in extra operations.
进阶变体
外企场景- arrow_right_alt
Modify the problem to allow incrementing character counts instead of only deletions.
- arrow_right_alt
Restrict the string to only vowels and optimize deletions to equalize their frequencies.
- arrow_right_alt
Introduce a maximum allowed deletion limit and find if making frequencies equal is possible under that constraint.