File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public List <String > removeInvalidParentheses (String s ) {
3+ List <String > result = new ArrayList <>();
4+
5+ if (s == null ) {
6+ return result ;
7+ }
8+
9+ Queue <String > q = new LinkedList <>();
10+ Set <String > visited = new HashSet <>();
11+
12+ q .offer (s );
13+ visited .add (s );
14+
15+ boolean finished = false ;
16+
17+ while (!q .isEmpty ()) {
18+ s = q .poll ();
19+
20+ if (isValid (s )) {
21+ result .add (s );
22+ finished = true ;
23+ }
24+
25+ if (finished ) {
26+ continue ;
27+ }
28+
29+ for (int i = 0 ; i < s .length (); i ++) {
30+ if (s .charAt (i ) != '(' && s .charAt (i ) != ')' ) {
31+ continue ;
32+ }
33+
34+ String t = s .substring (0 , i ) + s .substring (i + 1 );
35+
36+ if (!visited .contains (t )) {
37+ q .offer (t );
38+ visited .add (t );
39+ }
40+ }
41+ }
42+
43+ return result ;
44+ }
45+
46+ private boolean isValid (String s ) {
47+ int count = 0 ;
48+
49+ for (int i = 0 ; i < s .length (); i ++) {
50+ if (s .charAt (i ) == '(' ) {
51+ count ++;
52+ }
53+ if (s .charAt (i ) == ')' && count -- == 0 ) {
54+ return false ;
55+ }
56+ }
57+
58+ return count == 0 ;
59+ }
60+ }
You can’t perform that action at this time.
0 commit comments