LeetCode 题解工作台
反转每对括号间的子串
给出一个字符串 s (仅含有小写英文字母和括号)。 请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。 注意,您的结果中 不应 包含任何括号。 示例 1: 输入: s = "(abcd)" 输出: "dcba" 示例 2: 输入: s = "(u(love)i)" 输出:…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 栈·状态
答案摘要
我们可以直接用栈来模拟反转的过程。 时间复杂度 ,空间复杂度 ,其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给出一个字符串 s(仅含有小写英文字母和括号)。
请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。
注意,您的结果中 不应 包含任何括号。
示例 1:
输入:s = "(abcd)" 输出:"dcba"
示例 2:
输入:s = "(u(love)i)" 输出:"iloveu" 解释:先反转子字符串 "love" ,然后反转整个字符串。
示例 3:
输入:s = "(ed(et(oc))el)" 输出:"leetcode" 解释:先反转子字符串 "oc" ,接着反转 "etco" ,然后反转整个字符串。
提示:
1 <= s.length <= 2000s中只有小写英文字母和括号- 题目测试用例确保所有括号都是成对出现的
解题思路
方法一:模拟
我们可以直接用栈来模拟反转的过程。
时间复杂度 ,空间复杂度 ,其中 为字符串 的长度。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.