99
1010class RemoveInvalidParentheses {
1111 func removeInvalidParentheses( _ s: String ) -> [ String ] {
12- var res = [ String] ( ) , s = Array ( s . characters )
12+ var paths = [ String] ( )
1313
14- dfs ( & res , s , 0 , 0 , ( Character ( " ( " ) , Character ( " ) " ) ) )
14+ dfs ( & paths , Array ( s ) , 0 , 0 , ( " ( " , " ) " ) )
1515
16- return res
16+ return paths
1717 }
1818
19- private func dfs( _ res : inout [ String ] , _ s: [ Character ] , _ lastI : Int , _ lastJ : Int , _ parens: ( Character , Character ) ) {
20- var stack = 0 , s = s
19+ fileprivate func dfs( _ paths : inout [ String ] , _ s: [ Character ] , _ lastValid : Int , _ lastRight : Int , _ parens: ( Character , Character ) ) {
20+ var counter = 0 , s = s
2121
22- for i in lastI ..< s. count {
22+ for i in lastValid ..< s. count {
2323 if s [ i] == parens. 0 {
24- stack += 1
25- }
24+ counter += 1
25+ }
2626 if s [ i] == parens. 1 {
27- stack -= 1
27+ counter -= 1
2828 }
2929
30- if stack < 0 {
31- for j in lastJ... i {
32- if s [ j] == parens. 1 && ( j == lastJ || s [ j - 1 ] != parens. 1 ) {
33- dfs ( & res, Array ( s [ 0 ..< j] + s[ j + 1 ..< s. count] ) , i, j, parens)
30+ if counter < 0 {
31+ for j in lastRight... i {
32+ guard s [ j] == parens. 1 else {
33+ continue
34+ }
35+ guard j == 0 || s [ j] != s [ j - 1 ] || j == lastRight else {
36+ continue
3437 }
38+
39+ dfs ( & paths, Array ( s [ 0 ..< j] + s[ j + 1 ..< s. count] ) , i, j, parens)
3540 }
41+ // jump over invalid ones
3642 return
3743 }
3844 }
3945
4046 if parens. 0 == " ( " {
41- dfs ( & res , s. reversed ( ) , 0 , 0 , ( Character ( " ) " ) , Character ( " ( " ) ) )
47+ dfs ( & paths , s. reversed ( ) , 0 , 0 , ( " ) " , " ( " ) )
4248 } else {
43- res . append ( String ( s. reversed ( ) ) )
49+ paths . append ( String ( s. reversed ( ) ) )
4450 }
4551 }
4652}
0 commit comments