class Solution:
def longestValidParentheses(self, s: str) -> int:
size = len(s)
dp = [0] * size
res = 0
for i in range(1,size):
if s[i] == ")":
if s[i-1] == "(":
if i >= 2:
dp[i] = dp[i-2] + 2
else:
dp[i] = 2
elif (i-dp[i-1])>0 and s[i-dp[i-1]-1] == "(":
if i-dp[i-1] >= 2:
dp[i] = dp[i-1] + dp[i-dp[i-1]-2] + 2
else:
dp[i] = dp[i-1] + 2
res = max(res, dp[i])
return res
[LeetCode Python] 32. Longest Valid Parentheses动态规划
最新推荐文章于 2022-09-09 00:10:56 发布