-
Notifications
You must be signed in to change notification settings - Fork 0
/
L1249-MinimumRemoveToMakeValidParentheses.java
60 lines (59 loc) · 1.63 KB
/
L1249-MinimumRemoveToMakeValidParentheses.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
// https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
class Solution {
public String minRemoveToMakeValid(String s) {
StringBuilder sb = new StringBuilder(s);
Stack<Integer> stack = new Stack<>();
int length = sb.length();
for (int i = 0; i < length; i++) {
if (sb.charAt(i) == '(')
stack.push(i + 1);
if (sb.charAt(i) == ')') {
if (!stack.isEmpty() && stack.peek() >= 0)
stack.pop();
else
stack.push(-(i + 1));
}
}
while (!stack.isEmpty()) {
sb.deleteCharAt(Math.abs(stack.pop()) - 1);
}
return sb.toString();
}
// brute force
public String minRemoveToMakeValid2(String s) {
String res = "";
int count = 0;
int length = s.length();
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c == '(') {
count += 1;
}
if (c == ')') {
if (count < 1) {
continue;
}
count -= 1;
}
res += c;
}
s = res;
res = "";
length = s.length();
count = 0;
for (int i = length - 1; i >= 0; i--) {
char c = s.charAt(i);
if (c == ')') {
count += 1;
}
if (c == '(') {
if (count < 1) {
continue;
}
count -= 1;
}
res = c + res;
}
return res;
}
}