您的位置:首页 > 其它

32. Longest Valid Parentheses

2018-03-13 15:26 417 查看
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.
def longestValidParentheses(self, s):
s = ')' + s
dp = [0] * len(s)
for i in range(1, len(s)):
if s[i] == ')' and s[i - dp[i - 1] - 1] == '(':
dp[i] = dp[i - 1] + 2 + dp[i - 2 - dp[i - 1]]
return max(dp)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: