LeetCode 题解工作台

反转每对括号间的子串

给出一个字符串 s (仅含有小写英文字母和括号)。 请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。 注意,您的结果中 不应 包含任何括号。 示例 1: 输入: s = "(abcd)" 输出: "dcba" 示例 2: 输入: s = "(u(love)i)" 输出:…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 栈·状态

bolt

答案摘要

我们可以直接用栈来模拟反转的过程。 时间复杂度 ,空间复杂度 ,其中 为字符串 的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给出一个字符串 s(仅含有小写英文字母和括号)。

请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。

注意,您的结果中 不应 包含任何括号。

 

示例 1:

输入:s = "(abcd)"
输出:"dcba"

示例 2:

输入:s = "(u(love)i)"
输出:"iloveu"
解释:先反转子字符串 "love" ,然后反转整个字符串。

示例 3:

输入:s = "(ed(et(oc))el)"
输出:"leetcode"
解释:先反转子字符串 "oc" ,接着反转 "etco" ,然后反转整个字符串。

 

提示:

  • 1 <= s.length <= 2000
  • s 中只有小写英文字母和括号
  • 题目测试用例确保所有括号都是成对出现的
lightbulb

解题思路

方法一:模拟

我们可以直接用栈来模拟反转的过程。

时间复杂度 O(n2)O(n^2),空间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    def reverseParentheses(self, s: str) -> str:
        stk = []
        for c in s:
            if c == ")":
                t = []
                while stk[-1] != "(":
                    t.append(stk.pop())
                stk.pop()
                stk.extend(t)
            else:
                stk.append(c)
        return "".join(stk)
speed

复杂度分析

指标
时间complexity is O(n) because each character is pushed and popped at most once. Space complexity is O(n) due to the stack storing all characters and intermediate substrings for nested parentheses.
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Ask about handling nested parentheses and reversing inner substrings first.

  • question_mark

    Check understanding of stack-based state management for string transformations.

  • question_mark

    Expect explanation of why reversing at the closing parenthesis ensures correct output.

warning

常见陷阱

外企场景
  • error

    Failing to reverse only the substring within the current pair of parentheses.

  • error

    Ignoring nested parentheses and reversing the string globally too early.

  • error

    Not removing the parentheses from the final output, resulting in incorrect formatting.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Instead of reversing, rotate characters within each parentheses segment.

  • arrow_right_alt

    Use a queue instead of a stack to explore alternative traversal strategies.

  • arrow_right_alt

    Handle additional characters like digits or punctuation while reversing substrings.

help

常见问题

外企场景

反转每对括号间的子串题解:栈·状态 | LeetCode #1190 中等