LeetCode 题解工作台

删除字符串中的所有相邻重复项

给出由小写字母组成的字符串 s , 重复项删除操作 会选择两个相邻且相同的字母,并删除它们。 在 s 上反复执行重复项删除操作,直到无法继续删除。 在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。 示例: 输入: "abbaca" 输出: "ca" 解释: 例如,在 "abbaca" 中,…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 栈·状态

bolt

答案摘要

遍历字符串 `s` 中的每个字符 `c`,若栈为空或者栈顶值不等于字符 `c`,将 `c` 入栈,否则栈顶元素出栈。 最后返回栈中元素所组成的字符串。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给出由小写字母组成的字符串 s重复项删除操作会选择两个相邻且相同的字母,并删除它们。

s 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

 

示例:

输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。

 

提示:

  1. 1 <= s.length <= 105
  2. s 仅由小写英文字母组成。
lightbulb

解题思路

方法一:栈

遍历字符串 s 中的每个字符 c,若栈为空或者栈顶值不等于字符 c,将 c 入栈,否则栈顶元素出栈。

最后返回栈中元素所组成的字符串。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是字符串 s 的长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def removeDuplicates(self, s: str) -> str:
        stk = []
        for c in s:
            if stk and stk[-1] == c:
                stk.pop()
            else:
                stk.append(c)
        return ''.join(stk)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    They mention repeated removals causing new adjacent pairs, which is a strong signal to preserve evolving boundary state.

  • question_mark

    They ask for something better than simulating string deletions, which points away from costly rebuilds and toward a stack.

  • question_mark

    They emphasize that the final answer is unique, which supports a greedy left-to-right collapse strategy.

warning

常见陷阱

外企场景
  • error

    Rebuilding the string after every deletion, which turns a simple stack problem into repeated O(n) work.

  • error

    Using two pointers without stored history, which fails when a removal exposes a new match with an earlier surviving character.

  • error

    Forgetting that chain reactions matter, so the code removes one pair but misses the next pair created immediately after the pop.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Remove adjacent duplicates when a character appears k times in a row, which extends the stack to store counts.

  • arrow_right_alt

    Return the length of the final collapsed string instead of the string itself, while using the same stack process.

  • arrow_right_alt

    Process a stream of characters and maintain the current deduplicated result online with stack state.

help

常见问题

外企场景

删除字符串中的所有相邻重复项题解:栈·状态 | LeetCode #1047 简单