Skip to content

Commit d5d6446

Browse files
committed
Remove Outermost Parentheses
1 parent 99094a6 commit d5d6446

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

1021-remove-outermost-parentheses.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/remove-outermost-parentheses/
3+
4+
A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are
5+
valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()",
6+
and "(()(()))" are all valid parentheses strings.
7+
A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to
8+
split it into S = A+B, with A and B nonempty valid parentheses strings.
9+
Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k,
10+
where P_i are primitive valid parentheses strings.
11+
Return S after removing the outermost parentheses of every primitive string in the primitive
12+
decomposition of S.
13+
14+
Example 1:
15+
Input: "(()())(())"
16+
Output: "()()()"
17+
Explanation:
18+
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
19+
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
20+
21+
Example 2:
22+
Input: "(()())(())(()(()))"
23+
Output: "()()()()(())"
24+
Explanation:
25+
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
26+
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
27+
28+
Example 3:
29+
Input: "()()"
30+
Output: ""
31+
Explanation:
32+
The input string is "()()", with primitive decomposition "()" + "()".
33+
After removing outer parentheses of each part, this is "" + "" = "".
34+
35+
Note:
36+
S.length <= 10000
37+
S[i] is "(" or ")"
38+
S is a valid parentheses string
39+
"""
40+
class Solution:
41+
def removeOuterParentheses(self, S: str) -> str:
42+
res = []
43+
count = 0
44+
for parentheses in S:
45+
if count > 0 and parentheses == "(" or count > 1 and parentheses == ")":
46+
res.append(parentheses)
47+
if parentheses == "(":
48+
count += 1
49+
elif parentheses == ")":
50+
count -= 1
51+
return "".join(res)

0 commit comments

Comments
 (0)