[LeetCode]Longest Valid Parentheses 最长有效括号数
Longest Valid Parentheses 最长有效括号数
动态规划
end = i + 1 + dp[i+1]
1. dp[i] = dp[i+1] + 2 (if s[i] == '(' and s[end]== ')')
2. dp[i] += dp[end+1] (if end+1<len(s))
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
n = len(s)
dp = [0] * n
res = 0
for i in range(n-2, -1, -1):
if s[i] == '(':
right = i + 1 + dp[i+1]
if right < n and s[right] == ')':
dp[i] = dp[i+1] + 2
# 后面可能还有独立的括号
if right < n-1:
dp[i] += dp[right+1]
res = max(res, dp[i])
return res
栈
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
start = 0
stack = []
res = 0
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
if stack:
stack.pop()
# 表明仅仅匹配完一个区间的括号,还有剩余的括号
if stack:
res = max(i - stack[-1], res)
else: # 表明从start到i都是匹配的
res = max(i - start + 1, res)
else:
start = i + 1 # 过滤掉没用的)
return res
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法