动态规划求需要多少个字符使得其成为回文字符串
所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的,比如"aba"。当然,我们给你的问题不会再简单到判断一个字符串是不是回文字符串。现在要求你,给你一个字符串,可在任意位置添加字符,最少再添加几个字符,可以使这个字符串成为回文字符串。
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
int f[1001][1001];
char s[1001];
int main()
{
int n;
int lcs();
scanf("%d",&n);
while(n--)
{
printf("%d\n",lcs());
}
return 0;
}
int lcs()
{
int i,j;
scanf("%s",s);
memset(f,0,sizeof(f));
int length =strlen(s);
for(i=0;i<length;i++)
for(j=i;j>=0;j--)
{
if(s[i]==s[j])
f[i+1][j+1]=f[i][j+2];
else
f[i+1][j+1]=min(f[i][j+1],f[i+1][j+2])+1;
}
return f[length][1];
}}

浙公网安备 33010602011771号