Skip to content

Commit b5883c5

Browse files
authored
Update reverse-substrings-between-each-pair-of-parentheses.py
1 parent 1ce0d3f commit b5883c5

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

Python/reverse-substrings-between-each-pair-of-parentheses.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,34 @@
1-
# Time: O(n^2)
1+
# Time: O(n)
22
# Space: O(n)
33

44
class Solution(object):
5+
def reverseParentheses(self, s):
6+
"""
7+
:type s: str
8+
:rtype: str
9+
"""
10+
stk, lookup = [], {}
11+
for i, c in enumerate(s):
12+
if c == '(':
13+
stk.append(i)
14+
elif c == ')':
15+
j = stk.pop()
16+
lookup[i], lookup[j] = j, i
17+
result = []
18+
i, d = 0, 1
19+
while i < len(s):
20+
if s[i] == '(' or s[i] == ')':
21+
i = lookup[i]
22+
d *= -1
23+
else:
24+
result.append(s[i])
25+
i += d
26+
return "".join(result)
27+
28+
29+
# Time: O(n^2)
30+
# Space: O(n)
31+
class Solution2(object):
532
def reverseParentheses(self, s):
633
"""
734
:type s: str

0 commit comments

Comments
 (0)