描述
所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的,比如"aba"。当然,我们给你的问题不会再简单到判断一个字符串是不是回文字符串。现在要求你,给你一个字符串,可在任意位置添加字符,最少再添加几个字符,可以使这个字符串成为回文字符串。
-
输入
-
第一行给出整数N(0<N<100)
接下来的N行,每行一个字符串,每个字符串长度不超过1000.
输出
- 每行输出所需添加的最少字符数 样例输入
-
1 Ab3bd
样例输出
-
2
推荐指数:※※
来源:oj:http://acm.nyist.net/JudgeOnline/problem.php?pid=37
加一个字符,可能在尾部或者在头部,使得头尾匹配,在考虑其子问题。
一开始直接使用递归发现超时。那就在递归过程当中记录已经计算过的状态。dp;
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#include<string>
using namespace std;
const int N=1001;
int dp[N][N];
int count_step(char *str,int start,int last){
if(start>=last)
return 0;
if(str[start]==str[last]){
return count_step(str,start+1,last-1);
}
else
{
int i,t1,t2;
if(dp[start][last-1]==-1){//not calculate now
t1=count_step(str,start,last-1);//insert front
}
else
t1=dp[start][last-1];
if(dp[start+1][last]==-1){
t2=count_step(str,start+1,last);//insert last
}
else
t2=dp[start+1][last];
t1=min(t1,t2);
dp[start][last]=t1+1;
return t1+1;
}
}
int main()
{
char str[N];
int loops;
scanf("%d",&loops);
while(loops--){
scanf("%s",&str);
memset(dp,-1,sizeof(dp));
int min_step=count_step(str,0,strlen(str)-1);
printf("%d\n",min_step);
}
return 0;
}