Topic link: 22 Algorithm Design and Analysis - Dynamic Programming - Virtual Judge
Analysis: This topic is a relatively simple interval dynamic programming, but there is a pit that stuck me for a long time, so I want to analyze it here
Let f[i][j] denote the length of the longest palindrome substring from i to j
What I thought at first was that when s[i]==s[j], there is f[i][j]=f[i+1][j-1]+2, if s[i]!=s [j] has f[i][j]=0, but this is wrong, because i~j is a palindrome substring that requires not only s[i]==s[j], but also i+1~j -1 is also a palindrome substring , so when we know that s[i]==s[j], we cannot directly make f[i][j]=f[i+1][j-1]+2, and also It should be judged whether i+1~j-1 is a palindrome substring. At the beginning, I forgot to judge this condition, which led to wa twice. Another point to note is that an empty string is also a palindrome substring of length 1. So we can preprocess the palindrome string of length 2 first .
Here is the code:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>
#include<cmath>
#include<queue>
using namespace std;
const int N=1e3+10;
int f[N][N];
char s[N];
int main()
{
scanf("%s",s+1);
int l=strlen(s+1),ans=1;
for(int i=1;i<=l;i++) f[i][i]=1;
for(int i=1;i<l;i++)
if(s[i]==s[i+1]) f[i][i+1]=2,ans=2;
for(int len=3;len<=l;len++)
for(int i=1;i+len-1<=l;i++)
{
int j=i+len-1;
if((s[j]==s[i])&&(f[i+1][j-1])) f[i][j]=f[i+1][j-1]+2;
ans=max(ans,f[i][j]);
}
cout<<ans;
return 0;
}