Longest Valid Parentheses 最长合法括号
一、问题描述
给一个只由’(‘和’)'组成的字符串,找出其中最长的连续合法子串长度。(来源Leetcode)
样例
Input:(()
Output:2
Input: )()())
Output: 4
Input: ((())
Output: 4
二、解决方案
很明显,可以用动态规划,我也是这么想的。
1. 我的方案
构建dp[len][len], dp[i][j]表示以i开头,j结尾的子串中最长子串。s表示字符串,然后给出递推式
d p [ i ] [ j ] = { 2 , if i+1 = j and s[i] = ’(’ and s[j] = ’)’ d p [ i + 1 ] [ j − 1 ] + 2 , if dp[i+1][j-1] > 0 and s[i] = ’(’ and s[j] = ’)’ d p [ k + 1 ] [ j ] + d p [ i ] [ k ] , if dp[i][k] > 0 and dp[k+1][j] > 0, k ∈ ( i , j ) dp[i][j] = \begin {cases} 2, & \text{if i+1 = j and s[i] = '(' and s[j] = ')'}\\ dp[i+1][j-1] + 2, & \text{if dp[i+1][j-1] > 0 and s[i] = '(' and s[j] = ')'}\\ dp[k+1][j] + dp[i][k], & \text{if dp[i][k] > 0 and dp[k+1][j] > 0, } k \in (i, j)\\ \end {cases} dp[i][j]=⎩⎪⎨⎪⎧2,dp[i+1][j−1]+2,dp[k+1][j]+d