Skip to content

Commit

Permalink
[Stack] Add a solution to Longest Valid Parentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Nov 18, 2016
1 parent 835fb08 commit ea44a09
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions Stack/LongestValidParentheses.swift
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
}
}

0 comments on commit ea44a09

Please sign in to comment.