forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1021_Remove_outermost_parentheses
41 lines (36 loc) · 1020 Bytes
/
1021_Remove_outermost_parentheses
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
// https://leetcode.com/problems/remove-outermost-parentheses/
// My approach
public String removeOuterParentheses(String S) {
Stack<Character> stack = new Stack<Character>();
char []ch = S.toCharArray();
int count = 0;
String ans = "";
for(int i=0;i<ch.length;i++)
{
if(ch[i]=='(')
{
stack.push(ch[i]);
if(stack.size()>1)
ans+=ch[i];
}
else
{
stack.pop();
if(stack.size()>=1)
ans+=ch[i];
}
}
return ans;
}
// SOlution
class Solution {
public String removeOuterParentheses(String S) {
StringBuilder s = new StringBuilder();
int opened = 0;
for (char c : S.toCharArray()) {
if (c == '(' && opened++ > 0) s.append(c);
if (c == ')' && opened-- > 1) s.append(c);
}
return s.toString();
}
}