@@ -5,6 +5,17 @@ public List<String> removeInvalidParentheses(String s) {
5
5
return output ;
6
6
}
7
7
8
+ /*
9
+ We keep the openParen as '(' and closed as ')', we try to find an extra closed ')' that would make an invalid parenthesis
10
+ and we will remove it by skipping it and then keep checking for invalid parenthesis with iStart value as next i value and
11
+ jStart value as the index of j we removed the invalid parenthesis from. If we are done 'i' iterating over the string, we
12
+ reverse the string and now we check for invalid parenthesis with an extra '(' and so, we call the same code recursively.
13
+ once we are done, so we reverse back to original valid string and add to result. The control goes back to return statement
14
+ to find the next ')' since j goes from jStart to i.
15
+ The program only looks for valid answers which in this case if it is 'k', then time complexity would be O(nk) where n is
16
+ the length of the string.
17
+ */
18
+
8
19
public void removeHelper (String s , List <String > output , int iStart , int jStart , char openParen , char closedParen ) {
9
20
int numOpenParen = 0 , numClosedParen = 0 ;
10
21
for (int i = iStart ; i < s .length (); i ++) {
@@ -20,9 +31,9 @@ public void removeHelper(String s, List<String> output, int iStart, int jStart,
20
31
}
21
32
// No invalid closed parenthesis detected. Now check opposite direction, or reverse back to original direction.
22
33
String reversed = new StringBuilder (s ).reverse ().toString ();
23
- if (openParen == '(' )
34
+ if (openParen == '(' ) // to check wheteher we have just checked for the original version of the string or reverse.
24
35
removeHelper (reversed , output , 0 , 0 , ')' ,'(' );
25
36
else
26
- output .add (reversed );
37
+ output .add (reversed ); // we have checked both the original and reversed version.
27
38
}
28
39
}
0 commit comments