-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMinimumValidParentheses.java
More file actions
84 lines (58 loc) · 1.87 KB
/
Copy pathMinimumValidParentheses.java
File metadata and controls
84 lines (58 loc) · 1.87 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* leetcode: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
*/
import java.util.Map;
import java.util.HashMap;
import java.util.Stack;
import java.util.Set;
import java.util.TreeSet;
import java.util.SortedSet;
public class MinimumValidParentheses {
class SS {
int index;
char ch;
public SS(int index, char ch) {
this.index = index;
this.ch = ch;
}
}
public static void main(String[] args) {
assert minRemoveToMakeValid("a)b(c)d").equals("ab(c)d") == true;
}
public static String minRemoveToMakeValid(String s) {
public String minRemoveToMakeValid(String s) {
if (s.isEmpty()) {
return "";
}
Stack<SS> braces = new Stack<>();
Map<Character, Character> mapLetters = new HashMap<>();
mapLetters.put('{', '}');
mapLetters.put('[', ']');
mapLetters.put('(', ')');
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if(mapLetters.containsKey(ch)) {
braces.push(new SS(i, ch));
} else if (ch == ']' || ch == ')' || ch == '}' ) {
if (!braces.isEmpty() && mapLetters.get(braces.peek().ch) != null && mapLetters.get(braces.peek().ch) == ch) {
braces.pop();
}
else {
braces.push(new SS(i, ch));
}
}
}
StringBuilder sb = new StringBuilder();
boolean[] indices = new boolean[s.length()];
Iterator<SS> iter = braces.iterator();
while(iter.hasNext()){
indices[iter.next().index] = true;
}
for (int i = 0; i < s.length(); i++) {
if (!indices[i]) {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}