forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Stack] Add a solution to Longest Valid Parentheses
- Loading branch information
Yi Gu
committed
Nov 18, 2016
1 parent
835fb08
commit ea44a09
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
/** | ||
* 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 { | ||
let sChars = Array(s.characters) | ||
var stack = [Int]() | ||
var longest = 0 | ||
|
||
for (i, char) in sChars.enumerated() { | ||
if char == "(" || stack.isEmpty || sChars[stack.last!] == ")" { | ||
stack.append(i) | ||
} else { | ||
let _ = stack.removeLast() | ||
if stack.isEmpty { | ||
longest = max(longest, i + 1) | ||
} else { | ||
longest = max(longest, i - stack.last!) | ||
} | ||
} | ||
} | ||
|
||
return longest | ||
} | ||
} |