1 #include <iostream> 2 #include <string.h> 3 #include <string> 4 #include <fstream> 5 #include <algorithm> 6 #include <stdio.h> 7 #include <vector> 8 #include <queue> 9 #include <set> 10 #include <cmath> 11 using namespace std; 12 const double eps = 1e-8; 13 const int INF=0x7fffffff; 14 #define MAXN 1002 15 string s; 16 int ans[MAXN]; 17 int find(int cur) 18 { 19 for(int i=cur-1;i>=0;i--) 20 if(s[i]==s[cur])return i; 21 return cur; 22 } 23 bool check(int a,int b) 24 { 25 // cout<<s.substr(a,b-a+1)<<endl; 26 a--;b--; 27 if(a==b)return false; 28 while(a<b) 29 { 30 if(s[a]==s[b]){a++;b--;} 31 else return false; 32 } 33 return true; 34 } 35 int main() 36 { 37 int T; 38 scanf("%d",&T); 39 while(T--) 40 { 41 cin>>s; 42 int len=s.length(); 43 ans[0]=0; 44 for(int i=1;i<=len;i++) 45 { 46 ans[i]=INF; 47 for(int j=1;j<=i;j++) 48 if(check(j,i))ans[i]=min(ans[i],ans[j-1]+1); 49 else ans[i]=min(ans[i],ans[j-1]+i-j+1); 50 // cout<<ans[i]<<endl; 51 } 52 printf("%d\n",ans[len]); 53 } 54 return 0; 55 }
ans[i]=min(ans[i], j到i 是回文串 ans[j-1]+1 ,j到i不是回文串 ans[j-1]+i-j+1)