-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path1021.java
More file actions
65 lines (58 loc) · 2.17 KB
/
1021.java
File metadata and controls
65 lines (58 loc) · 2.17 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
__________________________________________________________________________________________________
sample 1 ms submission
class Solution {
public String removeOuterParentheses(String S) {
// asusume S would not be null
char[] sChar = S.toCharArray();
StringBuilder builder = new StringBuilder();
int count = 1; // the count of "("
for(int i = 1 ; i < sChar.length ; i++) {
char ch = sChar[i];
if( ch == '(' ) {
count++;
} else { // ch == ')'
count--;
}
if(count == 0) { // outer start and end index
i++;
count = 1;
continue;
} else {
builder.append( ch );
}
}
return builder.toString();
}
}
__________________________________________________________________________________________________
sample 34804 kb submission
class Solution {
public String removeOuterParentheses(String S) {
List<String> primitives = new ArrayList();
int counter = 0;
//Stack<Character> paranthesisStack = new Stack<Character>();
StringBuilder primitiveBuilder = new StringBuilder();
for (char c : S.toCharArray()) {
if(c == '(') {
counter++;
primitiveBuilder.append(c);
}
if(c == ')'){
counter--;
primitiveBuilder.append(c);
}
if(counter == 0) {
//primitive identified
primitives.add(primitiveBuilder.toString());
primitiveBuilder.setLength(0);
}
}
List<String> updatedPrimitives = primitives.stream()
.map( string -> string.substring(1,string.length()-1))
.collect(Collectors.toList());
primitiveBuilder.setLength(0);
updatedPrimitives.stream().forEach(string -> primitiveBuilder.append(string));
return primitiveBuilder.toString();
}
}
__________________________________________________________________________________________________