-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1190.Reverse-Substrings-Between-Each-Pair-of-Parentheses.py
63 lines (50 loc) · 1.49 KB
/
1190.Reverse-Substrings-Between-Each-Pair-of-Parentheses.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# https://leetcode.com/problems/day-of-the-week/
# Easy (54.07%)
# Total Accepted: 3,078
# Total Submissions: 5,692
# beats 100.0 % of python submissions
from collections import deque
class Solution(object):
def reverseParentheses(self, s):
"""
:type s: str
:rtype: str
"""
stack = deque()
pre = 0
res = []
idx = 0
length = len(s)
while idx < length:
if s[idx] == '(':
if not stack:
res.append(s[pre:idx])
else:
stack[-1] = stack[-1] + s[pre:idx]
i = idx + 1
while s[i] != '(' and s[i] != ')':
i += 1
if s[i] == '(':
stack.append(s[idx + 1:i])
idx = i
else:
tmp = s[idx + 1:i][::-1]
if not stack:
res.append(tmp)
else:
stack[-1] = stack[-1] + tmp
idx = i + 1
pre = idx
elif s[idx] == ')':
prefix = stack.pop()
tmp = prefix + s[pre:idx]
if not stack:
res.append(tmp[::-1])
else:
stack[-1] = stack[-1] + tmp[::-1]
idx += 1
pre = idx
else:
idx += 1
res.append(s[pre:])
return ''.join(res)