题目描述
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
解题思路
解题方法参考了该链接 https://blog.csdn.net/accepthjp/article/details/52439449
总结一下,DP思想。
代码 (Python3)
class Solution:
def longestValidParentheses(self, s: str) -> int:
s = ')' + s
dp = [0 for _ in range(len(s))]
ans = 0
for i in range(1, len(s)):
if s[i] == ')':
if s[i - 1 - dp[i - 1]] == '(':
dp[i] = dp[i - 1] + 2
dp[i] += dp[i - dp[i]]
ans = max(ans, dp[i])
return ans