forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParentheses.swift
More file actions
31 lines (27 loc) · 926 Bytes
/
LongestValidParentheses.swift
File metadata and controls
31 lines (27 loc) · 926 Bytes
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
/**
* Question Link: https://leetcode.com/problems/longest-valid-parentheses/
* Primary idea: Push index to a stack and pop encountering ")"
* Time Complexity: O(n), Space Complexity: O(n)
*/
class LongestValidParentheses {
func longestValidParentheses(_ s: String) -> Int {
var stack = [Int](), longest = 0, start = 0
for (i, char) in s.enumerated() {
if char == "(" {
stack.append(i)
} else {
if !stack.isEmpty {
stack.removeLast()
if let last = stack.last {
longest = max(longest, i - last)
} else {
longest = max(longest, i - start + 1)
}
} else {
start = i + 1
}
}
}
return longest
}
}