码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-02-25 19:13:20      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:pen   turn   tab   enumerate   end   action   匹配   char   form   

 

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)

标签:pen   turn   tab   enumerate   end   action   匹配   char   form   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!