LeetCode 题解工作台
操作后字符串的最短长度
给你一个字符串 s 。 你需要对 s 执行以下操作 任意 次: 选择一个下标 i ,满足 s[i] 左边和右边都 至少 有一个字符与它相同。 删除 i 左边 离它 最近 的 s[i] 字符。 删除 i 右边 离它 最近 的 s[i] 字符。 请你返回执行完所有操作后, s 的 最短 长度。 示例 1…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 哈希·表·结合·string
答案摘要
我们可以统计字符串中每个字符出现的次数,然后遍历计数数组,如果字符出现的次数为奇数,则最后该字符剩余 个,如果字符出现的次数为偶数,则最后该字符剩余 个。我们可以将所有字符的剩余个数相加,即为最终字符串的长度。 时间复杂度 ,其中 为字符串 的长度。空间复杂度 ,其中 为字符集的大小,本题中 $|\Sigma| = 26$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个字符串 s 。
你需要对 s 执行以下操作 任意 次:
- 选择一个下标
i,满足s[i]左边和右边都 至少 有一个字符与它相同。 - 删除
i左边 离它 最近 的s[i]字符。 - 删除
i右边 离它 最近 的s[i]字符。
请你返回执行完所有操作后, s 的 最短 长度。
示例 1:
输入:s = "abaacbcbb"
输出:5
解释:
我们执行以下操作:
- 选择下标 2 ,然后删除下标 0 和 3 处的字符,得到
s = "bacbcbb"。 - 选择下标 3 ,然后删除下标 0 和 5 处的字符,得到
s = "acbcb"。
示例 2:
输入:s = "aa"
输出:2
解释:
无法对字符串进行任何操作,所以返回初始字符串的长度。
提示:
1 <= s.length <= 2 * 105s只包含小写英文字母。
解题思路
方法一:计数
我们可以统计字符串中每个字符出现的次数,然后遍历计数数组,如果字符出现的次数为奇数,则最后该字符剩余 个,如果字符出现的次数为偶数,则最后该字符剩余 个。我们可以将所有字符的剩余个数相加,即为最终字符串的长度。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 ,其中 为字符集的大小,本题中 。
class Solution:
def minimumLength(self, s: str) -> int:
cnt = Counter(s)
return sum(1 if x & 1 else 2 for x in cnt.values())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Can the candidate quickly implement a solution using a hash table to count frequencies?
- question_mark
Does the candidate consider all edge cases like an already minimal string or no removable pairs?
- question_mark
Is the candidate aware of the importance of focusing only on character frequencies for an optimized solution?
常见陷阱
外企场景- error
Ignoring edge cases where no adjacent pairs exist and not optimizing for a direct frequency-based solution.
- error
Incorrectly handling cases with an odd number of identical characters that can’t fully form pairs.
- error
Overcomplicating the solution by attempting to manually remove pairs instead of focusing on character frequencies.
进阶变体
外企场景- arrow_right_alt
What happens if the string is composed entirely of unique characters?
- arrow_right_alt
Can this problem be solved using a stack approach instead of hash tables?
- arrow_right_alt
How does the time complexity change when considering strings of varying lengths or different characters?