Palindrome 回文

Palindrome

Problem Description
A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome.

As an example, by inserting 2 characters, the string “Ab3bd” can be transformed into a palindrome (“dAb3bAd” or “Adb3bdA”). However, inserting fewer than 2 characters does not produce a palindrome.

Input
Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from ‘A’ to ‘Z’, lowercase letters from ‘a’ to ‘z’ and digits from ‘0’ to ‘9’. Uppercase and lowercase letters are to be considered distinct.

Output
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.

Sample Input
5
Ab3bd

Sample Output
2

题目大意:输入一个数字,代表字符串的长度,输入一个字符串,判断最少插入多少个字符能使其变为回文串(正序与反序相同)。

所求结果 = 字符串长度 - 字符串与其反转字符串的最长子序列(子序列可以不是连续的)
要用到LCS算法(最长公共子序列),LCS中会用到动态规划,而在定义时要注意,题中给出字符串长度的范围为3 <= N <= 5000,定义一个 dp[5000][5000] 会栈溢出,即使定义为全局变量也不够。所以这里用到了滚动数组
滚动数组其实就是循环利用一些空间,从而达到优化空间的目的。最简单的解释就是在DP状态转移方程中,对我们而言有需要的仅仅是之前两个或者几个状态,在递推求解时,我们便可以利用这样一个便利解题。

题解代码:

#include<stdio.h>
#include<string.h>
#define Max(a,b) a>b?a:b
int main()
{
    int i,j,n,dp[2][5005];
    char str[5005],str2[5005];
    while(~scanf("%d",&n))
    {
        getchar();
        gets(str);
        memset(dp,0,sizeof(dp));
        for(i = 0,j = n-1; str[i]!='\0'; i++,j--)
        {
            str2[i] = str[j];
        }
        for(i = 0; str[i]!='\0'; i++)
        {
            for(j = 0; str2[j]!='\0'; j++)
            {
                if(str[i] == str2[j])
                {
                    dp[(i+1)%2][j+1] = dp[i%2][j]+1;
                }
                else
                {
                    dp[(i+1)%2][j+1] = Max(dp[i%2][j+1],dp[(i+1)%2][j]);
                }
            }
        }
        printf("%d\n",n-dp[n%2][n]);
    }
    return 0;
}

参考:
LCS:https://blog.csdn.net/SongBai1997/article/details/81866559
滚动数组:https://blog.csdn.net/caizi1991/article/details/24908877

hncu2021acm1—1005

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值