forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_301.java
85 lines (70 loc) · 1.84 KB
/
_301.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
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
85
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
/**
* 301. Remove Invalid Parentheses
*
* 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())()"]
")(" -> [""]
*/
public class _301 {
public static class Solution1 {
public List<String> removeInvalidParentheses(String s) {
List<String> result = new ArrayList<>();
if (s == null) {
return result;
}
Set<String> visited = new HashSet();
Queue<String> q = new LinkedList();
q.offer(s);
visited.add(s);
boolean found = false;
while (!q.isEmpty()) {
String curr = q.poll();
if (isValid(curr)) {
found = true;
result.add(curr);
}
if (found) {
continue;//this means if the initial input is already a valid one, we'll just directly return it and there's actually only one valid result
}
for (int i = 0; i < curr.length(); i++) {
if (curr.charAt(i) != '(' && curr.charAt(i) != ')') {
continue;//this is to rule out those non-parentheses characters
}
String next = curr.substring(0, i) + curr.substring(i + 1);
if (!visited.contains(next)) {
q.offer(next);
visited.add(next);
}
}
}
return result;
}
private boolean isValid(String str) {
char[] chars = str.toCharArray();
int count = 0;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == '(') {
count++;
}
if (c == ')') {
count--;
if (count == -1) {
return false;
}
}
}
return count == 0;
}
}
}