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.
Subscribe to see which companies asked this question
python
class Solution(object):
def longestValidParentheses(self,s):
stack=[(-1,')')]
maxLen = 0
for i in range(len(s)):
if s[i]==')' and stack[-1][1]=='(':
stack.pop()
maxLen = max(maxLen,i-stack[-1][0])
else:
stack.append((i,s[i]))
return maxLen
CC=Solution()
s="()"
print CC.longestValidParentheses(s)