首页 > 其他 > 详细

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

时间:2018-02-25 18:00:02      阅读:181      评论:0      收藏:0      [点我收藏+]
 

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)

原文:https://www.cnblogs.com/zle1992/p/8469694.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!