【51 nod 1092】 回文字符串

基准时间限制:1 秒 空间限制:131072 KB 分值: 10  难度:2级算法题
 收藏
 关注
回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。每个字符串都可以通过向中间添加一些字符,使之变为回文字符串。
例如:abbc 添加2个字符可以变为 acbbca,也可以添加3个变为 abbcbba。方案1只需要添加2个字符,是所有方案中添加字符数量最少的。
Input
输入一个字符串Str,Str的长度 <= 1000。
Output
输出最少添加多少个字符可以使之变为回文字串。
Input示例
abbc
Output示例
2


直接用字符串的长度减去该字符串与取反后的该字符串的LCS的长度即可;

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
#define MAXN 1050
char c[MAXN];
char d[MAXN];
int dp[MAXN][MAXN];
int main()
{
	cin>>c;
	int l=strlen(c);
	strcpy(d,c);
	reverse(d,d+l);
	memset(dp,0,sizeof(dp));
	for(int i=0;i<l;i++)
	{
		for(int j=0;j<l;j++)
		{
			if(c[i]==d[j])
			{
				dp[i+1][j+1]=dp[i][j]+1;
			}
			else
			{
				dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]); 
			}
		}
	}
	cout<<l-dp[l][l]<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/duanghaha/article/details/80572903