Transferred from: http://blog.csdn.net/cfc1243570631/article/details/9304525
Title Description:
Given A string containing just the characters ' (' and ') ', find the length of the longest valid (well-formed) parentheses Su Bstring.
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.
Translation:
Given a string containing ' (' and ') ', find out the length of the longest valid brace matching substring.
Solution:
This problem can be solved with one-dimensional dynamic programming in inverse way. Suppose the input parenthesis expression is string s, maintaining a one-dimensional array of length s.length dp[], and array elements initialized to 0. Dp[i] represents the longest valid matching brace substring length from s[i] to S[s.length-1] that contains s[i]. The following relationship exists: dp[s.length-1] = 0; I from n-2, 0 reverse dp[], and record its maximum value. If s[i] = = ' (', then the value of Dp[i] is calculated from I to s.length-1 in S. This calculation is divided into two steps, via Dp[i + 1] (note dp[i + 1] has been solved in the previous step): Looking for a valid brace matching substring length starting from i + 1 in S, that is, Dp[i + 1], skipping this valid brace substring, viewing the next character, with the subscript j = i + 1 + dp[i + 1]. If J does not cross over and s[j] = = ') ', then S[i ... j] is a valid brace match, dp[i] =dp[i + 1] + 2. After a valid match length of s[i ... j] is obtained, if J + 1 does not cross the bounds, then the value of Dp[i] is added to the longest valid match starting with J + 1, i.e. Dp[j + 1].
[CPP] View plain copy #include <stdio.h> #include <string.h> #define N 65536 int longestvalidparentheses (const char *s) { int i,j,n; int dp[N]; int max=0; n=strlen (s); for (i=0;i<n;i++) dp[i]=0; for (i=n-2;i>=0;i--) { if (s[i]== ' (') { j=i+1+dp[i+1] ; if (j<n && s[j]== ') ') { dp[i]=dp[i+1]+2; if (j+1<n) dp[i]+=dp[j+1]; } } if (Max<=dp[i]) max=dp[i]; } return max; } int main () { &NBSP;&NBSP;&NBSP; const char *s= ")) () ()"; printf ("% D\n ", longestvalidparentheses (s)); return 0; }