-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
41 lines (35 loc) · 1.05 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution:
def reverseParentheses(self, s: str) -> str:
parentheses = []
open_indices = []
chars = []
for c in s:
if c == "(":
open_indices.append(len(chars))
elif c == ")":
parentheses.append((open_indices.pop(), len(chars)))
else:
chars.append(c)
for l, r in parentheses:
chars[l:r] = chars[l:r][::-1]
return "".join(chars)
class Solution:
def reverseParentheses(self, s: str) -> str:
pairs = {}
opens = []
for i, c in enumerate(s):
if c == "(":
opens.append(i)
elif c == ")":
l, r = opens.pop(), i
pairs[l], pairs[r] = r, l
result = []
i, direction = 0, 1
for _ in range(len(s)):
if i in pairs:
i = pairs[i]
direction = -direction
else:
result.append(s[i])
i += direction
return "".join(result)