51nod 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


笨方法                   ans=len-最长公共子序列

#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
char a[10001];
char b[10001];
int dp[10001][1001];
int main(){
    memset(dp,0,sizeof(dp));
      cin>>a;
    int len=strlen(a);
    for(int j=len-1;j>=0;j--){
        b[len-1-j]=a[j];
    }
    for(int j=1;j<=len;j++){
        for(int k=1;k<=len;k++){
            if(a[j-1]==b[k-1]){
                dp[j][k]=dp[j-1][k-1]+1;
            }
            else{
                dp[j][k]=max(dp[j-1][k],dp[j][k-1]);
            }
        }
    }
    int ans=len-dp[len][len];
    cout<<ans<<endl;
}


看到了一个动态规划的代码 看了好半天 

决定复制过来

一道动态规划题,辅助空间cost[i][j]表示要将从s[j]个字符开始长度为i的子串变为对称串需要添加的字符个数;这样,动态方程为:

cost[0][i] = cost[1][i] = 0;//长度为0和长度为1的串

cost[i][j] = 当s[j] == s[i+j-1]时,字符串长度加2,需要增加的字符个数相同,即cost[i][j] = cost[i-2][j+1];

                 否则,cost[i][j] = min{cost[i-1][j], cost[i-1][j+1]} + 1;


#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
char s[1002];
int f[1001][1001];
int main()
{
    int tcases, n, i, j;
    cin >> tcases;
   // while(tcases--)
   // {
        scanf("%s", s);
        n = strlen(s);
        memset(f, 0, sizeof(f));
        for(i = 0; i < n; i++)
        {
            f[0][i] = 0;
            f[1][i] = 0;
        }
        for(i = 2; i <= n; i++)
            for(j = 0; j < n; j++)
            {
                if(s[j] == s[i+j-1])
                {
                    f[i][j] = f[i-2][j+1];
                }
                else if(f[i-1][j] < f[i-1][j+1])
                {
                    f[i][j] = f[i-1][j] + 1;
                }
                else f[i][j] = f[i-1][j+1] + 1;
            }
        printf("%d\n", f[n][0]);
    //}
    return 0;
}

还是自己写的比较精炼

#include<bits/stdc++.h>
using namespace std;
char a[10001];
int dp[1001][10001];
int main(){
    cin>>a;
    int len=strlen(a);
    for(int j=2;j<=len;j++){
        for(int i=0;i<len;i++){
            int k=i+j-1;
            
          
            if(a[i]==a[k]){
                dp[i][k]=dp[i+1][k-1];
            }
            else{
                dp[i][k]=min(dp[i][k-1]+1,dp[i+1][k]+1);
            }
            //cout<<dp[i][k]<<endl;
        }
    }
    cout<<dp[0][len-1]<<endl;

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值