forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRemoveInvalidParentheses.java
More file actions
84 lines (76 loc) · 2.44 KB
/
Copy pathRemoveInvalidParentheses.java
File metadata and controls
84 lines (76 loc) · 2.44 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package backtracking;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by gouthamvidyapradhan on 17/10/2017.
* Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Examples:
"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]
Solution: O(N x 2 ^ N) generate all combination of unique parentheses and return a list of valid parentheses which
has the string length maximum
*/
public class RemoveInvalidParentheses {
/**
* Main method
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception{
List<String> result = new RemoveInvalidParentheses().removeInvalidParentheses("()())()");
result.forEach(System.out::println);
}
public List<String> removeInvalidParentheses(String s) {
Set<String> set = new HashSet<>();
List<String> result = new ArrayList<>();
result.add("");
//generate all combinations of unique parentheses
for(int i = s.length() - 1; i >= 0; i --){
for(int j = 0, l = result.size(); j < l; j++){
String curr = s.charAt(i) + result.get(j);
if(!set.contains(curr)){
result.add(curr);
set.add(curr);
}
}
}
//check for max length
int maxLen = 0;
for(String r : result){
if(isValid(r)){
maxLen = Math.max(maxLen, r.length());
}
}
//prepare the final list
List<String> finalR = new ArrayList<>();
for(String r : result){
if(isValid(r)) {
if(r.length() == maxLen){
finalR.add(r);
}
}
}
return finalR;
}
/**
* Check if the given string of parentheses is valid or not
* @param s String of parentheses
* @return true if valid
*/
private boolean isValid(String s){
int count = 0;
for(int i = 0, l = s.length(); i < l; i ++){
if(s.charAt(i) == '('){
count ++;
} else if(s.charAt(i) == ')'){
count --;
if(count < 0) return false;
}
}
return count == 0;
}
}