-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack1021.java
More file actions
33 lines (29 loc) · 964 Bytes
/
Stack1021.java
File metadata and controls
33 lines (29 loc) · 964 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
package stack;
import java.util.Stack;
public class Stack1021 {
public static void main(String[] args) {
String input = "(()())(())(()(()))";
System.out.println(removeOuterParentheses(input));
}
public static String removeOuterParentheses(String S) {
Stack<Character> stack = new Stack<>();
StringBuilder result = new StringBuilder();
char[] chars = S.toCharArray();
StringBuilder temp = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
temp.append(chars[i]);
if (chars[i] == '(') {
stack.push(chars[i]);
continue;
}
if (chars[i] == ')' ) {
stack.pop();
}
if (stack.isEmpty()) {
result.append(temp.substring(1, temp.length()-1));
temp.delete(0, temp.length());
}
}
return result.toString();
}
}