題目出處
1190. Reverse Substrings Between Each Pair of Parentheses
難度
medium
題目分類
String, Stack, Bracket Sequences
2026-09-28 一刷
個人範例程式碼 - 一刷 (2026/09/28)
class Solution:
def reverseParentheses(self, s: str) -> str:
lefts = []
pairs = {}
for i, c in enumerate(s):
if c == '(':
lefts.append(i)
elif c == ')':
left = lefts.pop()
pairs[left] = i
pairs[i] = left
# teleport when pair matches
# ex: a(bc)d
# a -> ( teleport to ) -> c b -> ( teleport to ) -> end
# ex: [a(bc)d]
# [ teleport to ] -> d -> ) teleport to ( -> b c ->
# ) teleport to ( -> a -> [ teleport to ] -> end
ans = []
idx = 0
step = 1
while 0 <= idx < len(s):
if idx in pairs: # teleport
idx = pairs[idx]
step = -step
else:
ans.append(s[idx])
idx += step # move next, skip ()
return "".join(ans)
算法說明
直接解是使用stack存待反轉的字串,然後最後找到右括弧進行反轉,需要約 O(n*k) 可能 TLE,
這個解法是用一個傳送的概念,先記憶左右括弧,進行雙向傳送。
每傳送一次就轉向一次,並繼續走到遇到下一個括弧,再傳送回原來位置,之後往下一個走。
Time Complexity
O(n)
Space Complexity
O(n) # pairs