-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathRemove Invalid Parenthesis
64 lines (47 loc) · 1.5 KB
/
Remove Invalid Parenthesis
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
//Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
package gfg;
import java.util.ArrayList;
import java.util.List;
public class RemoveInvalidParenthesis {
public static List<String> removeInvalidParentheses(String s) {
ArrayList<String> result = new ArrayList<String>();
if (s == null)
return result;
dfs(s, "", 0, 0, result);
if (result.size() == 0) {
result.add("");
}
return result;
}
public static void dfs(String left, String right, int countLeft, int maxLeft, ArrayList<String> result) {
int max = 0;
if (left.length() == 0) {
if (countLeft == 0 && right.length() != 0) {
if (maxLeft > max) {
max = maxLeft;
}
if (maxLeft == max && !result.contains(right)) {
result.add(right);
}
}
return;
}
if (left.charAt(0) == '(') {
dfs(left.substring(1), right + "(", countLeft + 1, maxLeft + 1, result);// keep (
dfs(left.substring(1), right, countLeft, maxLeft, result);// drop (
} else if (left.charAt(0) == ')') {
if (countLeft > 0) {
dfs(left.substring(1), right + ")", countLeft - 1, maxLeft, result);
}
dfs(left.substring(1), right, countLeft, maxLeft, result);
} else {
dfs(left.substring(1), right + String.valueOf(left.charAt(0)), countLeft, maxLeft, result);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "())()";
List<String> ans = removeInvalidParentheses(str);
System.out.println(ans);
}
}