思路:dp[i][j]表示区间(i,j)中回文串的个数,那么dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];如果str[i]==str[j],那么dp[i][j]+=dp[i+1][j-1]+1;
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #define Maxn 1010 #define Mod 10007 using namespace std; int dp[Maxn][Maxn]; int main() { int t,i,j,n,Case=0; char str[Maxn]; scanf("%d",&t); while(t--) { scanf("%s",&str); n=strlen(str); memset(dp,0,sizeof(dp)); for(i=0;i<=n;i++) dp[i][i]=1; for(i=0;i<n;i++) { for(j=i-1;j>=0;j--) { dp[j][i]=(dp[j+1][i]+dp[j][i-1]-dp[j+1][i-1]+Mod)%Mod; if(str[j]==str[i]) { dp[j][i]+=dp[j+1][i-1]+1; dp[j][i]%=Mod; } } } printf("Case %d: %d ",++Case,dp[0][n-1]%Mod); } return 0; }