1047. Remove All Adjacent Duplicates In String
模拟栈
You are given a string s
consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s
until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
Example 1:
Example 2:
Constraints:
1 <= s.length <= 10
5
s
consists of lowercase English letters.
分析
栈的应用
使用栈结构来高效地检测和删除相邻重复字符。
遍历字符串
s
的每个字符:如果栈顶元素与当前字符相同,则弹出栈顶(发现相邻重复)。
否则,将当前字符压入栈中。
遍历结束后,栈中剩下的字符即为最终结果。
如果要求空间复杂度为 O(1)(例如处理极大字符串),可以用双指针模拟栈,直接在原字符串上修改(需转为可变类型如列表)。
res[slow - 1]
才是“栈顶”元素,因为slow
指向的是下一个写入位置。res[slow]
是未初始化的位置,不能用于比较(否则可能访问越界或错误数据)。
Last updated
Was this helpful?