51nod 1092 回文字符串(dp或LCS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BBHHTT/article/details/82117882

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

思路:我的做法就是字符串长度-原串和逆串的最长公共子串长度。后来又看了一个dp的做法,见最后代码

博客:https://blog.csdn.net/liuyanfeier/article/details/50756701

#include<iostream>   
#include<cstdio>
#include<map>
#include<cstring>  
using  namespace  std;    
int  dp[1005][2005];
char a[1005];
char b[1005];
int  main()    
{
	int n;
	scanf("%s",a);
	int  len  =  strlen(a);    
	for(int i=0;i<len;i++) {
		b[i]=a[len-i-1];
	}
	memset(dp,0,sizeof(dp));
	for(int  i  =  1;  i  <=  len;  i++) {
	   	for(int  j  =  1;  j  <=  len;  j++) {    
	        if(a[i-1]  ==  b[j-1])
	        	dp[i][j]  =  dp[i-1][j-1]  +  1;    
	        else
				dp[i][j]  =max(dp[i-1][j],dp[i][j-1]);        
	        }
		}
		printf("%d\n",len-dp[len][len]);
	return 0;
}

dp做法:

这种解法相对来说就是一般的dp思想,没有什么套路。

我们尝试将给出的字符串的所有子串都找到,怎么划分呢。可以按子串的起始位置和长度来划分。

dp[i][j]表示的是从第i个字符开始长度为j的子串变为回文串需要添加的最少字母数,最终要求并的是dp[0][n]

递推公式看代码,有了上面的思路递推公式就比较简单了

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
 
int const maxn = 1005 ;
int dp[maxn][maxn] ;
//dp[i][j] 表示的是从第i个字符开始长度为j的子串变为回文串需要添加的最少字母数
//最终要求的结果为dp[0][n]
char str[maxn];
 
int main()
{
    while(scanf("%s",str)!=EOF)
    {
        int n = strlen(str);
        memset(dp,0,sizeof(dp));
        //初始化,明显长度为0以及长度为1的子串本身就为回文串,添加的字母数为0
        for(int i = 0 ; i < n ; i++)
        {
            dp[i][0] = dp[i][1] = 0 ;
        }
        for(int j = 2 ; j <= n ; j++)
        {
            for(int i = 0 ; i < n ; i++)
            {
                //j为长度,i子串的起始位置
                if(str[i]==str[i+j-1])
                {
                    //子串的首尾字符相同,那么它的结果就和去掉首尾字符烦人子串一样
                    dp[i][j] = dp[i+1][j-2];
                }
                else dp[i][j] = min(dp[i][j-1],dp[i+1][j-1])+1 ;
                //子串首尾字符不相同的话,那么就去掉首或者尾然后加上1
            }
        }
        printf("%d\n",dp[0][n]);
    }
    return 0 ;
}

猜你喜欢

转载自blog.csdn.net/BBHHTT/article/details/82117882