-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveInvalidParenthesis.java
More file actions
55 lines (41 loc) · 1.25 KB
/
RemoveInvalidParenthesis.java
File metadata and controls
55 lines (41 loc) · 1.25 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
package BackTracking;
import java.util.*;
public class RemoveInvalidParenthesis {
public List<String> removeInvalidParentheses(String s) {
List<String> res = new ArrayList<>();
HashSet<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.add(s);
visited.add(s);
boolean found = false;
while (!queue.isEmpty()) {
s = queue.poll();
if (isValid(s)) {
res.add(s);
found = true;
}
if (found) continue;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '(' && s.charAt(i) != ')')
continue;
String t = s.substring(0, i) + s.substring(i + 1);
if (!visited.contains(t)) {
queue.add(t);
visited.add(t);
}
}
}
return res;
}
boolean isValid(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(')
count++;
if (c == ')' && count-- == 0)
return false;
}
return count == 0;
}
}