forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove_Outermost_parentheses.java
More file actions
50 lines (40 loc) · 951 Bytes
/
Remove_Outermost_parentheses.java
File metadata and controls
50 lines (40 loc) · 951 Bytes
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
42
43
44
45
46
47
48
49
import java.util.*;
import java.lang.*;
import java.io.*;
class Stacks {
public String removeOuterParentheses(String S) {
if (S.length() == 0) return "";
Stack<Character> stack = new Stack<>();
int count = 0;
for (int i = S.length() - 1; i > 0; i--)
stack.push(S.charAt(i));
String ans = "";
while (!stack.isEmpty()){
if (stack.peek() == '('){
if (count >= 0)
ans+= stack.peek();
count++;
}
else{
if (count != 0)
ans += stack.peek();
count --;
}
stack.pop();
}
return ans;
}
}
/*
TIME COMPLEXITY: 0(N) where n is size of string
SPACE COMPLEXITY:0(N) where n is size of string
TEST CASE
INPUT
"(()())(())"
OUTPUT
"()()()"
INPUT
"(()())(())(()(()))"
OUTPUT
"()()()()(())"
*/