Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())
" Output: 4 Explanation: The longest valid parentheses substring is"()()"
class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype: int """ n = len(s) if n == 0 or n == 1: return 0 dp = [0] * n # dp[i]存储以i为结尾的最长有效匹配长度 for i in range(1,n): if ")" == s[i]: pre = i - dp[i-1] -1 if pre >=0 and s[pre] == "(": dp[i] = dp[i-1] + 2 if pre > 0: dp[i] += dp[pre-1] return max(dp)