变成回文字符串所需要的次数-动态规划

描述
所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的,比如"aba"。当然,我们给你的问题不会再简单到判断一个字符串是不是回文字符串。现在要求你,给你一个字符串,可在任意位置添加字符,最少再添加几个字符,可以使这个字符串成为回文字符串。
输入
第一行给出整数N(0<N<100)
接下来的N行,每行一个字符串,每个字符串长度不超过1000.
输出
每行输出所需添加的最少字符数
样例输入
1
Ab3bd
样例输出
2

推荐指数:※※

来源:oj:http://acm.nyist.net/JudgeOnline/problem.php?pid=37

加一个字符,可能在尾部或者在头部,使得头尾匹配,在考虑其子问题。

一开始直接使用递归发现超时。那就在递归过程当中记录已经计算过的状态。dp;

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#include<string>
using namespace std;
const int N=1001;
int dp[N][N];
int count_step(char *str,int start,int last){
	if(start>=last)
		return 0;
	if(str[start]==str[last]){
		return count_step(str,start+1,last-1);
	}
	else
	{
		int i,t1,t2;
		if(dp[start][last-1]==-1){//not calculate now
		    t1=count_step(str,start,last-1);//insert front 
		}
		else
			t1=dp[start][last-1];
		if(dp[start+1][last]==-1){
			t2=count_step(str,start+1,last);//insert last
		}
		else
			t2=dp[start+1][last];
		t1=min(t1,t2);
		dp[start][last]=t1+1;
		return t1+1;
		}
}
int main()
{
	char str[N];
	int loops;
	scanf("%d",&loops);
	while(loops--){
		scanf("%s",&str);
		memset(dp,-1,sizeof(dp));
		int min_step=count_step(str,0,strlen(str)-1);
		printf("%d\n",min_step);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值