Repository navigation
Expand file tree
/
Copy pathRemoveInvalidPar.java
More file actions
64 lines (58 loc) · 1.69 KB
/
Copy pathRemoveInvalidPar.java
File metadata and controls
64 lines (58 loc) · 1.69 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
import java.util.*;
public class RemoveInvalidPar {
Set<String> result = new HashSet<>();
public List<String> removeInvalidParentheses(String s) {
int openR = 0;
int closeR = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
openR++;
} else if (c == ')') {
if (openR > 0) {
openR--;
} else {
closeR++;
}
}
}
check(s, 0, 0, new StringBuilder(), openR, closeR);
return new ArrayList<>(result);
}
private void check(
String s,
int pos,
int bal,
StringBuilder sb,
int openR,
int closeR
) {
if (pos == s.length()) {
if (bal == 0 && openR == 0 && closeR == 0) {
result.add(sb.toString());
}
return;
}
char c = s.charAt(pos);
if (c == '(') {
if (openR > 0) {
check(s, pos + 1, bal, sb, openR - 1, closeR);
}
sb.append(c);
check(s, pos + 1, bal + 1, sb, openR, closeR);
sb.deleteCharAt(sb.length() - 1);
} else if (c == ')') {
if (closeR > 0) {
check(s, pos + 1, bal, sb, openR, closeR - 1);
}
if (bal > 0) {
sb.append(c);
check(s, pos + 1, bal - 1, sb, openR, closeR);
sb.deleteCharAt(sb.length() - 1);
}
} else {
sb.append(c);
check(s, pos + 1, bal, sb, openR, closeR);
sb.deleteCharAt(sb.length() - 1);
}
}
}