32. Longest Valid Parentheses
https://leetcode.com/problems/longest-valid-parentheses/
Python
Stack
- Time: O(N)
- Space: O(N)
class Solution:
def longestValidParentheses(self, s: str) -> int:
max_length = 0
stack = []
stack.append((-1, ')'))
for i, char in enumerate(s):
if char == ')' and stack[-1][1] == '(':
stack.pop()
max_length = max(max_length, i-stack[-1][0])
else:
stack.append((i, char))
return max_length