One or two-dimensional dynamic programming, timed out
int longestvalidparentheses (string s) {
int Len=s.length (), maxlen=0;
BOOL Valid[len][len]; VALID[I][J] Indicates whether S[I]...S[J] is a valid string
memset (valid,false,sizeof (valid));
for (int i=0;i+1<len;i++)
if (s[i]== ' (' &&s[i+1]== ') ') {
Valid[i][i+1]=true;
maxlen=2;
}
for (int k=3;k<len;k=k+2) {//k = interval
for (int i=0;i+k<len;i++) {
for (int j=i+1;j+1<i+k;j=j+2)
if (Valid[i][j]&&valid[j+1][i+k]) {
Valid[i][i+k]=true;
maxlen=k+1;
Break
}
}
}
return maxlen;
}
Two or one-dimensional dynamic planning
int longestvalidparentheses (string s) {
int Len=s.length (), maxlen=0;
int Dp[len]; Dp[i] indicates the longest valid string length starting from s[i]
Memset (Dp,0,sizeof (DP));
for (int i=len-2;i>=0;i--)
if (s[i]== ' (') {
int j=i+1+dp[i+1];
if (j<len&&s[j]== ') ') {
dp[i]=j-i+1;
if (J+1<len)
DP[I]+=DP[J+1];
}
Maxlen=max (Maxlen,dp[i]);
}
return maxlen;
}
Three, Stack,o (n), go through it all over again
int longestvalidparentheses (string s) {
Stack<int> St;
int maxlen=0,acclen=0;
for (int i=0;i<s.length (); i++)
if (s[i]== ' (')
St.push (i);
else{
if (St.empty ())
acclen=0;
else{
int Matchedpos=st.top ();
St.pop ();
int matchedlen=i-matchedpos+1;
if (St.empty ()) {
Acclen+=matchedlen;
Matchedlen=acclen;
}
Else
Matchedlen=i-st.top ();
Maxlen=max (Maxlen,matchedlen);
}
}
return maxlen;
}