Given a string containing just the characters '('
and ')'
,
find the length of the longest valid (well-formed) parentheses substring.
For "(()"
, the longest valid parentheses substring is "()"
,
which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring is "()()"
,
which has length = 4.
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
s = ')' + s
stack, result = [], 0
for index in range(len(s)):
element = s[index]
if element == ')' and stack and stack[-1][1] == '(':
stack.pop()
result = max(result, index - stack[-1][0])
else:
stack.append((index, s[index]))
return result