-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveOuterParentheses.java
More file actions
36 lines (33 loc) · 1.16 KB
/
Copy pathRemoveOuterParentheses.java
File metadata and controls
36 lines (33 loc) · 1.16 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
import java.util.*;
/*
Remove the outermost parentheses of every
primitive string in the primitive decomposition of S
Example:
Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
*/
public class RemoveOuterParentheses {
public static void main(String[] args) {
System.out.println(findAndremoveOuterParenthesesFrom("(()())(())"));
}
public static String findAndremoveOuterParenthesesFrom(String inputString){
ArrayList<Integer> openBraces = new ArrayList<>();
char[] chars = inputString.toCharArray();
String result = "";
for(int i=0; i< chars.length; i++){
if(chars[i] == '('){
openBraces.add(i);
}else {
int endIndex = openBraces.size() - 1;
if (openBraces.size() == 1) {
result = result + inputString.substring(openBraces.get(endIndex)+1, i);
}
openBraces.remove(endIndex);
}
}
return result;
}
}