Longest Valid parentheses
Given A string containing just the characters ‘(‘
‘)‘
and, find the length of the longest valid (well-formed) parenthe SES substring.
"(()"
for, the longest valid parentheses substring "()"
are, which has length = 2.
Another example ")()())"
is, where the longest valid parentheses substring "()()"
are, which has length = 4.
Dp[i] Indicates the length of the longest valid pair of parentheses, starting from s[i] (including S[i]) and reaching s[n-1]. If s[i]== ' (' We need to check if the parentheses of the j=dp[i+1]+i+1 corresponding s[j] position are "), if S[J] is ') ' then the parentheses are formed, so dp[i]=dp[i+1]+2 at the same time, we need to continue to consider dp[j+1] If the j+1 is not out of range, then dp[i]=dp[i+1]+2+dp[j+1] other conditions dp[i]=0;
1 classSolution {2 Public:3 intLongestvalidparentheses (strings) {4 intn=s.length ();5 if(n==0)return 0;6 7 int*dp=New int[n];8dp[n-1]=0;9 Ten intresult=0; One for(inti=n-2; i>=0; i--) A { - if(s[i]=='(') - { the intj=dp[i+1]+i+1; - - if(s[j]==')') - { +dp[i]=dp[i+1]+2; - if(j<n-1) dp[i]+=dp[j+1]; + } A Else at { -dp[i]=0; - } - - if(dp[i]>result) - { inresult=Dp[i]; - } to } + Else - { thedp[i]=0; * } $ }Panax Notoginseng Delete [] DP; - returnresult; the } +};
"Leetcode" longest Valid parentheses