⚡Flashcard Drill➔
NeetCode #362LC-1190MediumStack
← Back to All Problems

#362 · #1190 · Reverse Substrings Between Each Pair of Parentheses(反转每对括号间的子串)

📌 Problem Statement & Constraints

You are given a string s consisting of lowercase letters and parentheses. Reverse the substrings inside each pair of matching parentheses, starting from the innermost pair, and return the result. Constraints: 1 <= s.length <= 2000; the input is always valid.

💡 Core Algorithmic Approaches

  1. Keep a stack of string buffers, one per nesting level.
  2. On (, push a new empty buffer. On ), pop the innermost buffer, reverse it, and append it to the enclosing buffer.
  3. Letters are appended to the current (topmost) buffer.
  4. This resolves nesting automatically, because inner levels are reversed before being merged outward.

💻 Benchmark Python3 Implementation

class Solution:
    def reverseParentheses(self, s: str) -> str:
        st = [[]]                          # one buffer per nesting level
        for ch in s:
            if ch == "(":
                st.append([])              # enter a new level
            elif ch == ")":
                inner = st.pop()[::-1]     # reverse the completed level
                st[-1].extend(inner)
            else:
                st[-1].append(ch)
        return "".join(st[0])

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n^2) worst case, because reversing nested levels can copy the same characters repeatedly (depth d means up to d passes over each character).
💾 Space Complexity
O(n) for the buffers.

⚠️ Interview Pitfalls & Follow-ups

  • Reversing before popping: the order is pop, then reverse, then extend into the parent.
  • Forgetting to start with an outer buffer: the top-level characters need somewhere to go.
  • Trying to find matching parentheses with a stack of indices: workable, but the buffer stack is much shorter to write and just as clear.
  • Reversing the whole string at the end: only the parenthesised substrings are reversed, and they nest.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Stack Problems

中文速览与面试要点

反转每对括号间的子串

给出一个字符串 s(仅含有小写英文字母和括号)。请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。注意,您的结果中 不应 包含任何括号。约束:1 ≤ s.length ≤ 2000;s 中只有小写英文字母和括号;题目数据保证所有括号都是成对出现的。

核心要点

  • 栈存字符列表(标准解) :栈的初始元素是一个空列表,表示最外层的字符串。
  • 遇到 ( :压入一个新的空列表,表示进入新一层。
  • 遇到 ) :弹出栈顶(内层结果), 反转 后追加到新的栈顶(外层结果)末尾。
  • 遇到字母 :追加到当前栈顶列表中。
  • 为什么反转发生在 ) 处 :括号内的内容在遇到 ) 时已经完整,此时反转并合并到外层,符合「从内到外逐层反转」的语义。

常见陷阱

  • 在 ( 处反转 :括号内容尚未完整,必须等到 ) 时再反转。
  • extend(sub[::-1]) 写成 extend(sub) :忘记反转会导致结果错误。
  • 用字符串而非列表 :字符串拼接是 O(n),整体会退化为 O(n²);用列表 + extend 更高效。
  • 栈的初始元素忘记放空列表 :会导致 stack[-1].append(c) 报错。

参考实现

class Solution:
    def reverseParentheses(self, s: str) -> str:
        stack = [[]]                # 栈的每个元素是「当前层已收集的字符列表」
        for c in s:
            if c == '(':
                stack.append([])    # 进入新的一层
            elif c == ')':
                sub = stack.pop()   # 内层结果
                stack[-1].extend(sub[::-1])     # 反转后追加到外层
            else:
                stack[-1].append(c)
        return ''.join(stack[0])