Skip to content

Commit 49d15b1

Browse files
1021 Remove Outermost Parentheses.py
1 parent 79b31de commit 49d15b1

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed

1021 Remove Outermost Parentheses.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
#!/usr/bin/python3
2+
"""
3+
A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where
4+
A and B are valid parentheses strings, and + represents string concatenation.
5+
For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.
6+
7+
A valid parentheses string S is primitive if it is nonempty, and there does not
8+
exist a way to split it into S = A+B, with A and B nonempty valid parentheses
9+
strings.
10+
11+
Given a valid parentheses string S, consider its primitive decomposition:
12+
S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.
13+
14+
Return S after removing the outermost parentheses of every primitive string in
15+
the primitive decomposition of S.
16+
17+
Example 1:
18+
Input: "(()())(())"
19+
Output: "()()()"
20+
Explanation:
21+
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
22+
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
23+
24+
Example 2:
25+
Input: "(()())(())(()(()))"
26+
Output: "()()()()(())"
27+
Explanation:
28+
The input string is "(()())(())(()(()))", with primitive decomposition
29+
"(()())" + "(())" + "(()(()))".
30+
After removing outer parentheses of each part, this is "()()" + "()" +
31+
"()(())" = "()()()()(())".
32+
33+
Example 3:
34+
Input: "()()"
35+
Output: ""
36+
Explanation:
37+
The input string is "()()", with primitive decomposition "()" + "()".
38+
After removing outer parentheses of each part, this is "" + "" = "".
39+
40+
41+
Note:
42+
S.length <= 10000
43+
S[i] is "(" or ")"
44+
S is a valid parentheses string
45+
"""
46+
from collections import deque
47+
48+
49+
class Solution:
50+
def removeOuterParentheses(self, S: str) -> str:
51+
"""
52+
Primitive parentheses will have equal number of opened and closed
53+
parentheses.
54+
55+
Use count
56+
Exclude the first and last parathesis
57+
"""
58+
ret = []
59+
cnt = 0
60+
for e in S:
61+
if e == "(":
62+
cnt += 1
63+
if cnt > 1:
64+
ret.append(e)
65+
else:
66+
cnt -= 1
67+
if cnt > 0:
68+
ret.append(e)
69+
70+
return "".join(ret)
71+
72+
73+
def removeOuterParentheses_error(self, S: str) -> str:
74+
"""
75+
stack + deque
76+
"""
77+
ret = []
78+
stk = []
79+
cur_q = deque()
80+
for e in S:
81+
if e == "(":
82+
stk.append(e)
83+
else:
84+
prev = stk.pop()
85+
if stk:
86+
cur_q.appendleft(prev)
87+
cur_q.append(e)
88+
else:
89+
ret.extend(cur_q)
90+
cur_q = deque()
91+
92+
return "".join(ret)
93+
94+
95+
if __name__ == "__main__":
96+
assert Solution().removeOuterParentheses("(()())(())(()(()))") == "()()()()(())"

0 commit comments

Comments
 (0)