Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created April 10, 2021 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/fcb8384816d1f2bd5356e52c1e744e2b to your computer and use it in GitHub Desktop.
Save vrat28/fcb8384816d1f2bd5356e52c1e744e2b to your computer and use it in GitHub Desktop.
Longest Valid Parenthesis (Leetcode 32)
class Solution {
func longestValidParentheses(_ s: String) -> Int {
var maxLength = 0
var stack = [Int]()
stack.append(-1)
for (index,elem) in s.enumerated(){
if elem == "(" {
stack.append(index)
}
else {
stack.popLast()
if let last = stack.last {
maxLength = max(maxLength, index - last)
}
else{
stack.append(index)
}
}
}
return maxLength
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment