-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathMinRemove.java
61 lines (41 loc) · 1.18 KB
/
MinRemove.java
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
public String minRemoveToMakeValid(String s) {
int open = 0, close = 0;
for(int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if(ch == ')') close++;
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if(ch == '(') {
if(open >= close) continue;
open++;
} else if(ch == ')') {
close--;
if(open == 0) continue;
open--;
}
sb.append(ch);
}
return sb.toString();
}
public String minRemoveToMakeValid(String s) {
Stack<Integer> st = new Stack<>();
for(int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if(ch == '(') {
st.push(i);
} else if(ch == ')'){
if(!st.isEmpty() && s.charAt(st.peek()) == '(') st.pop();
else st.push(i);
}
}
HashSet<Integer> set = new HashSet<>();
while(!st.isEmpty()) set.add(st.pop());
// Without HashMap
StringBuilder ans = new StringBuilder();
for(int i=0; i<s.length(); i++) {
if(!set.contains(i)) ans.append(s.charAt(i));
}
return ans.toString();
}