File tree 1 file changed +13
-10
lines changed
1 file changed +13
-10
lines changed Original file line number Diff line number Diff line change 6
6
7
7
class LongestValidParentheses {
8
8
func longestValidParentheses( _ s: String ) -> Int {
9
- let sChars = Array ( s. characters)
10
- var stack = [ Int] ( )
11
- var longest = 0
9
+ var stack = [ Int] ( ) , longest = 0 , start = 0
12
10
13
- for (i, char) in sChars . enumerated ( ) {
14
- if char == " ( " || stack . isEmpty || sChars [ stack . last! ] == " ) " {
11
+ for (i, char) in s . enumerated ( ) {
12
+ if char == " ( " {
15
13
stack. append ( i)
16
14
} else {
17
- let _ = stack. removeLast ( )
18
- if stack. isEmpty {
19
- longest = max ( longest, i + 1 )
15
+ if !stack. isEmpty {
16
+ stack. removeLast ( )
17
+
18
+ if let last = stack. last {
19
+ longest = max ( longest, i - last)
20
+ } else {
21
+ longest = max ( longest, i - start + 1 )
22
+ }
20
23
} else {
21
- longest = max ( longest , i - stack . last! )
24
+ start = i + 1
22
25
}
23
26
}
24
27
}
25
28
26
29
return longest
27
30
}
28
- }
31
+ }
You can’t perform that action at this time.
0 commit comments