NYOJ 37 动态规划 回文字符串

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
/*
状态: cost[i][j] 表示要将 str 从第j个字符开始,
    长度为i的子串变为回文串需要添加的字符个数.这样
转移方程为:
     cost[0][i] = cost[1][i] = 0; (长度为0和长度为1的串)
当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;
*/

int dp[1010][1010];
char str[1010];
int main()
{
    int N;
    scanf("%d%*c", &N);
    while (N--)
    {
        gets(str);
        int len = strlen(str);

        for (int i = 0; i < len; i++)//
            dp[1][i] = dp[0][i] = 0;

        for (int i = 2; i <= len; i++)
            for (int j = 0; j <= len-i; j++)
            {
                if (str[j] == str[j+i-1])
                    dp[i][j] = dp[i-2][j+1];
                else
                    dp[i][j] = min(dp[i-1][j], dp[i-1][j+1]) + 1;
            }
        printf("%d\n", dp[len][0]);
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值