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.
code1:
()():返回2
1 class Solution: 2 def longestValidParentheses(self, s): 3 ans = 0 4 stack = [] 5 for i,item in enumerate(s): 6 if item == '(': 7 stack.append(i) 8 else: 9 if(stack != []): 10 ans = max(ans,i-stack[-1]+1) 11 stack.pop() 12 return ans
code2:
()():返回4
不是很理解
1 class Solution: 2 def longestValidParentheses(self, s): 3 ans = 0 4 stack = [] 5 last =-1 6 for i,item in enumerate(s): 7 if item == '(': 8 stack.append(i) 9 else: 10 if(stack == []):#已经匹配成功了 11 last = i 12 else: 13 stack.pop() 14 if stack==[]: 15 ans = max(ans,i-last) 16 else: 17 ans = max(ans,i-stack[-1]) 18 return ans