-
Notifications
You must be signed in to change notification settings - Fork 0
/
0032_longest_valid_parentheses.swift
42 lines (39 loc) · 1.28 KB
/
0032_longest_valid_parentheses.swift
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
// https://leetcode.com/problems/longest-valid-parentheses/
class Solution {
func longestValidParentheses(_ s: String) -> Int {
let sa = Array(s)
var longest = 0
var leftArray = [Int]()
var startedIndex = -1
for (i, c) in sa.enumerated() {
if startedIndex == -1 {
// not started counting
if c == ")" {
continue
} else {
startedIndex = i
leftArray.append(i)
}
} else {
if c == "(" {
leftArray.append(i)
} else {
// c == ")"
if leftArray.count == 0 {
startedIndex = -1
} else if leftArray.count == 1 {
leftArray.removeLast()
let length = i - startedIndex + 1
longest = max(longest, length)
} else {
leftArray.removeLast()
let last = leftArray.last!
let length = i - last
longest = max(longest, length)
}
}
}
}
return longest
}
}