您的位置:首页 > 其它

51nod 1092 回文字符串

2016-09-14 18:14 381 查看
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

首先 我们知道什么是回文字符串

然后 他说要最少

= =

其实这样想

我们把字符串倒过来 和原来的字符串对比 首先公共的位置对齐 然后不一样的地方- - 就是对不齐的地方添点就好了- -

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
string a;
while(cin>>a)
{
short int dp[1005][1005];
memset(dp,0,sizeof(dp));

int l=strlen(&a[0]);
int i,j;
for(i=1;i<=l;i++)
{
for(j=1;j<=l;j++)
{
if(a[i-1]==a[l-j])dp[i][j]=dp[i-1][j-1]+1;
else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
cout<<l-dp[l][l]<<endl;
}
}


懒得用滚动数组了- -
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: