32. Longest Valid Parentheses(最长括号匹配,hard)

Posted 张乐乐章

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了32. Longest Valid Parentheses(最长括号匹配,hard)相关的知识,希望对你有一定的参考价值。

 

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

 

以上是关于32. Longest Valid Parentheses(最长括号匹配,hard)的主要内容,如果未能解决你的问题,请参考以下文章

32. Longest Valid Parentheses

32. Longest Valid Parentheses

32. Longest Valid Parentheses *HARD*

32. Longest Valid Parentheses

32. Longest Valid Parentheses

32. Longest Valid Parentheses