您的位置:首页 > 编程语言 > Python开发

32. Longest Valid Parentheses leetcode python new season 2016

2016-01-18 14:35 603 查看
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.

class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
s = ')' + s
stack, result = [], 0
for index in range(len(s)):
element = s[index]
if element == ')' and stack and stack[-1][1] == '(':
stack.pop()
result = max(result, index - stack[-1][0])
else:
stack.append((index, s[index]))
return result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: