题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2631
/*
Sample Input
3
racecar
fastcar
aaadbccb
Sample Output
1
7
3
题意:一串字符串,添加多少元素可以构成回文字符串,
如果本身就是的话,则只能添加一个
思路:对于每一个位置(i),都进行一次从1到i的判断,对i位置进行更新,取最小
*/
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
int dp[1010];
char a[1010];
bool judge(int x,int y)
{
while(x <= y)
{
if(a[x] != a[y]) ///不是回文字符串
return false;
x ++;
y --;
}
return true;
}
int main()
{
int t;
scanf("%d",&t);
while(t --)
{
scanf("%s",a+1);
int d = strlen(a + 1);
memset(dp,0,sizeof(dp));
for(int i = 1; i <= d; i ++)
{
dp[i] = i;///每个位置添加的最大可能
for(int j = 1; j <= i; j ++)
if(judge(j,i)) ///判断从j到i是否是回文字符串,是的话,往下进行
///1到i进行判断时可能存在多个回文字符串,每个都要进行更新,取最小
/*
例如aaaaaa,1,2,3,4,5到6都是回文字符串,j的值变化一次更新一次
*/
dp[i] = min(dp[i],dp[j-1] + 1);
}
printf("%d\n",dp[d]);
}
return 0;
}