forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
33 lines (33 loc) · 862 Bytes
/
Solution.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
class Solution {
public String minRemoveToMakeValid(String s) {
Deque<Character> stk = new ArrayDeque<>();
int x = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == ')' && x == 0) {
continue;
}
if (c == '(') {
++x;
} else if (c == ')') {
--x;
}
stk.push(c);
}
StringBuilder ans = new StringBuilder();
x = 0;
while (!stk.isEmpty()) {
char c = stk.pop();
if (c == '(' && x == 0) {
continue;
}
if (c == ')') {
++x;
} else if (c == '(') {
--x;
}
ans.append(c);
}
return ans.reverse().toString();
}
}