> For the complete documentation index, see [llms.txt](https://nataliekung.gitbook.io/ladder_code/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nataliekung.gitbook.io/ladder_code/meta-2025/1047.-remove-all-adjacent-duplicates-in-string.md).

# 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**.

&#x20;

**Example 1:**

<pre><code><strong>Input: s = "abbaca"
</strong><strong>Output: "ca"
</strong><strong>Explanation: 
</strong>For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
</code></pre>

**Example 2:**

<pre><code><strong>Input: s = "azxxzy"
</strong><strong>Output: "ay"
</strong></code></pre>

&#x20;

**Constraints:**

* `1 <= s.length <= 10`<sup>`5`</sup>
* `s` consists of lowercase English letters.

分析

#### **栈的应用**

1. **使用栈结构**来高效地检测和删除相邻重复字符。
2. 遍历字符串 `s` 的每个字符：
   * 如果**栈顶元素**与当前字符相同，则弹出栈顶（发现相邻重复）。
   * 否则，将当前字符压入栈中。
3. 遍历结束后，栈中剩下的字符即为最终结果。

如果要求空间复杂度为 O(1)（例如处理极大字符串），可以用**双指针模拟栈**，直接在原字符串上修改（需转为可变类型如列表）。

* **`res[slow - 1]` 才是“栈顶”元素**，因为 `slow` 指向的是下一个写入位置。
* **`res[slow]` 是未初始化的位置**，不能用于比较（否则可能访问越界或错误数据）。

```python3
class Solution:
    def removeDuplicates(self, s: str) -> str:
        if not s:
            return s
        res = list(s)
        slow=0
        for fast in range(len(res)):
            if slow > 0 and res[slow-1] == res[fast]:
                slow -= 1
            else:
                res[slow] = res[fast]
                slow += 1
        return ''.join(res[:slow])
            




```
