-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
57 lines (49 loc) · 1.63 KB
/
Copy pathsolution.java
File metadata and controls
57 lines (49 loc) · 1.63 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
class Solution {
// I verify if the parentheses count balances out to zero
private boolean isValid(String s) {
int count = 0;
for (char ch : s.toCharArray()) {
if (ch == '(')
count++;
else if (ch == ')') {
count--;
if (count < 0)
return false;
}
}
return count == 0;
}
public List<String> validParenthesis(String s) {
List<String> ans = new ArrayList<>();
Set<String> visited = new HashSet<>();
Queue<String> q = new LinkedList<>();
q.add(s);
visited.add(s);
boolean found = false;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
String curr = q.poll();
if (isValid(curr)) {
ans.add(curr);
found = true;
}
// Skip generating children if a solution is found at this level
if (found)
continue;
for (int j = 0; j < curr.length(); j++) {
if (curr.charAt(j) != '(' && curr.charAt(j) != ')')
continue;
String next = curr.substring(0, j) + curr.substring(j + 1);
if (!visited.contains(next)) {
visited.add(next);
q.add(next);
}
}
}
if (found)
break;
}
return ans;
}
}