forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path301_removeInvalidParentheses.java
47 lines (39 loc) · 1.43 KB
/
301_removeInvalidParentheses.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
40
41
42
43
44
45
46
47
public class Solution {
public List<String> removeInvalidParentheses(String s) {
List<String> result = new ArrayList<String>();
if(s == null) return result;
Queue<String> queue = new LinkedList<String>();
HashSet<String> set = new HashSet<String>();
queue.add(s);
set.add(s);
boolean found = false; //!!!
while(!queue.isEmpty()){
String t = queue.remove();
if(isValid(t)){
result.add(t);
found = true;
}
if(found) continue; // found in this level, so no need to add next level string in queue
for(int i = 0; i < t.length(); i++){
char c = t.charAt(i);
if(c != '(' && c != ')') continue; // ignore non-'(' and ')'
String cur = t.substring(0,i) + t.substring(i+1);
if(set.contains(cur)) continue; // queue already has similar one, ignore this one.
else{
queue.add(cur);
set.add(cur);
}
}
}
return result;
}
public boolean isValid(String s){
int count = 0;
for(char c: s.toCharArray()){
if(c == '(') count++;
if(c == ')') count --;
if(count < 0) return false;
}
return count == 0;
}
}