Created
April 10, 2021 07:45
-
-
Save vrat28/fcb8384816d1f2bd5356e52c1e744e2b to your computer and use it in GitHub Desktop.
Longest Valid Parenthesis (Leetcode 32)
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
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