-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinRemoveToMakeValid.java
39 lines (35 loc) · 1.19 KB
/
MinRemoveToMakeValid.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
class MinRemoveToMakeValid {
public String minRemoveToMakeValid(String s) {
/*
Runtime: 17 ms, faster than 92.16% of Java online submissions for Minimum Remove to Make Valid Parentheses.
Memory Usage: 42.8 MB, less than 95.25% of Java online submissions for Minimum Remove to Make Valid Parentheses.
*/
// Pass 1: Remove all invalid ")"
StringBuilder sb = new StringBuilder();
int openSeen = 0;
int balance = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
openSeen++;
balance++;
} if (c == ')') {
if (balance == 0) continue;
balance--;
}
sb.append(c);
}
// Pass 2: Remove the rightmost "("
StringBuilder result = new StringBuilder();
int openToKeep = openSeen - balance;
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if (c == '(') {
openToKeep--;
if (openToKeep < 0) continue;
}
result.append(c);
}
return result.toString();
}
}