-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain301.java
More file actions
65 lines (61 loc) · 1.95 KB
/
Main301.java
File metadata and controls
65 lines (61 loc) · 1.95 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
package HOT100;
import java.util.ArrayList;
import java.util.List;
public class Main301 {
private List<String> res = new ArrayList<>();
public List<String> removeInvalidParentheses(String s) {
int lRemove = 0;
int rRemove = 0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '(') {
lRemove++;
} else if(s.charAt(i) == ')') {
if(lRemove == 0) {
rRemove++;
} else {
lRemove--;
}
}
}
helper(s, 0, lRemove, rRemove);
return res;
}
private void helper(String str, int start, int lRemove, int rRemove) {
if(lRemove == 0 && rRemove == 0) {
if(isValid(str)) {
res.add(str);
}
}
for (int i = start; i < str.length(); i++) {
if(i != start && str.charAt(i) == str.charAt(i - 1)) {
continue;
}
// 如果剩余的字符无法满足去掉的数量要求,直接返回
if (lRemove + rRemove > str.length() - i) {
return;
}
// 尝试去掉一个左括号
if (lRemove > 0 && str.charAt(i) == '(') {
helper(str.substring(0, i) + str.substring(i + 1), i, lRemove - 1, rRemove);
}
// 尝试去掉一个右括号
if (lRemove > 0 && str.charAt(i) == ')') {
helper(str.substring(0, i) + str.substring(i + 1), i, lRemove, rRemove - 1);
}
}
}
private boolean isValid(String str) {
int cnt = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '(') {
cnt++;
} else if (str.charAt(i) == ')') {
cnt--;
if (cnt < 0) {
return false;
}
}
}
return cnt == 0;
}
}