LeetCode 题解工作台
删除字符串中的所有相邻重复项 II
给你一个字符串 s ,「 k 倍重复项删除操作」将会从 s 中选择 k 个相邻且相等的字母,并删除它们,使被删去的字符串的左侧和右侧连在一起。 你需要对 s 重复进行无限次这样的删除操作,直到无法继续为止。 在执行完所有删除操作后,返回最终得到的字符串。 本题答案保证唯一。 示例 1: 输入: s …
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 栈·状态
答案摘要
我们可以遍历字符串 ,维护一个栈,栈中存储的是字符和该字符出现的次数。当遍历到字符 时,如果栈顶元素的字符和 相同,则将栈顶元素的次数加一,否则将字符 和次数 入栈。当栈顶元素的次数等于 时,将栈顶元素出栈。 遍历完字符串 后,栈中存储的就是最终结果。我们可以将栈中的元素依次弹出,拼接成字符串即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给你一个字符串 s,「k 倍重复项删除操作」将会从 s 中选择 k 个相邻且相等的字母,并删除它们,使被删去的字符串的左侧和右侧连在一起。
你需要对 s 重复进行无限次这样的删除操作,直到无法继续为止。
在执行完所有删除操作后,返回最终得到的字符串。
本题答案保证唯一。
示例 1:
输入:s = "abcd", k = 2 输出:"abcd" 解释:没有要删除的内容。
示例 2:
输入:s = "deeedbbcccbdaa", k = 3 输出:"aa" 解释: 先删除 "eee" 和 "ccc",得到 "ddbbbdaa" 再删除 "bbb",得到 "dddaa" 最后删除 "ddd",得到 "aa"
示例 3:
输入:s = "pbbcggttciiippooaais", k = 2 输出:"ps"
提示:
1 <= s.length <= 10^52 <= k <= 10^4s中只含有小写英文字母。
解题思路
方法一:栈
我们可以遍历字符串 ,维护一个栈,栈中存储的是字符和该字符出现的次数。当遍历到字符 时,如果栈顶元素的字符和 相同,则将栈顶元素的次数加一,否则将字符 和次数 入栈。当栈顶元素的次数等于 时,将栈顶元素出栈。
遍历完字符串 后,栈中存储的就是最终结果。我们可以将栈中的元素依次弹出,拼接成字符串即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stk = []
for c in s:
if stk and stk[-1][0] == c:
stk[-1][1] = (stk[-1][1] + 1) % k
if stk[-1][1] == 0:
stk.pop()
else:
stk.append([c, 1])
ans = [c * v for c, v in stk]
return "".join(ans)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to manage stack operations effectively under constraints.
- question_mark
Handling edge cases such as no adjacent duplicates or very large inputs.
- question_mark
Efficient handling of string processing using stack-based state management.
常见陷阱
外企场景- error
Failing to correctly manage the stack during consecutive removals, leading to incorrect outputs.
- error
Not correctly handling cases where no characters can be removed, resulting in inefficient operations.
- error
Overcomplicating the problem by using unnecessary additional data structures.
进阶变体
外企场景- arrow_right_alt
Increase the value of k to test scalability.
- arrow_right_alt
Modify the input to include no adjacent duplicates and check if the solution performs optimally.
- arrow_right_alt
Test with large inputs to evaluate the time and space complexity of the solution.