32. Longest Valid Parentheses Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
1 2 3 Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()"
Example 2:
1 2 3 Input: ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()"
Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution (object) : def longestValidParentheses (self, s) : """ :type s: str :rtype: int """ stack = [0 ] longest = 0 for c in s: if c == "(" : stack.append(0 ) else : if len(stack) > 1 : val = stack.pop() stack[-1 ] += val + 2 longest = max(longest, stack[-1 ]) else : stack = [0 ] return longest