-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRemoveOutermostParentheses.java
More file actions
42 lines (32 loc) · 1.21 KB
/
RemoveOutermostParentheses.java
File metadata and controls
42 lines (32 loc) · 1.21 KB
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
// See: https://leetcode.com/problems/remove-outermost-parentheses/
package leetcode.stack;
import java.util.Stack;
public class RemoveOutermostParentheses {
// TODO: The performance can be enhanced
public String removeOuterParentheses(String S) {
Stack<Character> stack = new Stack<>();
StringBuilder decomp = new StringBuilder();
StringBuilder result = new StringBuilder();
for (int i = 0; i < S.length(); i++) {
char currChar = S.charAt(i);
if (currChar == '(') {
stack.push('(');
decomp.append('(');
} else if (!stack.empty()) {
stack.pop();
decomp.append(')');
}
if (stack.empty()) {
result.append(decomp.subSequence(1, decomp.length() - 1));
decomp.setLength(0);
}
}
return result.toString();
}
public static void main(String[] args) {
RemoveOutermostParentheses sln = new RemoveOutermostParentheses();
String input1 = "(()())(())(()(()))";
String output1 = "()()()()(())";
System.out.println(sln.removeOuterParentheses(input1).equals(output1));
}
}