Skip to content

Commit 4ab4de5

Browse files
committed
Remove outer most parantheses
1 parent 67de492 commit 4ab4de5

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
To remove the outermost parentheses of each primitive substring, we need to identify where each primitive starts and ends. A primitive ends when the number of opening and closing parentheses are equal. So, by counting '(' and ')', we can find each primitive and remove its outermost layer.
2+
3+
Use two counters:
4+
5+
count1 for the number of '('
6+
count2 for the number of ')'
7+
8+
Traverse the input string s character by character.
9+
10+
If count1 == count2, it means the previous primitive is completed, so reset both counters.
11+
12+
While inside a primitive (count1 != count2), skip adding the first opening '(' by checking count1 != 1.
13+
14+
Add all other characters to the output string, excluding the outermost parentheses.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
string removeOuterParentheses(string s) {
4+
int count1 = 0, count2 = 0;
5+
string out;
6+
7+
for (int i = 0; i < s.size(); i++) {
8+
if (s[i] == '(') {
9+
count1++;
10+
} else {
11+
count2++;
12+
}
13+
14+
if (count1 == count2) {
15+
count1 = 0;
16+
count2 = 0;
17+
}
18+
19+
if (count1 != count2 && count1 != 1) {
20+
out += s[i];
21+
}
22+
}
23+
24+
return out;
25+
}
26+
};

0 commit comments

Comments
 (0)