HDU 1513------Palindrome

Palindrome

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3641    Accepted Submission(s): 1252


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
 
题意:
给你一串字符串,可在任意位置添加字符,求使其变成回文串的最小添加个数。
题解:
回文串的意思是把这个字符串倒着跟正着长得一样。我们求解回文串的问题一般都会开个新的字符串保存倒着输入的当前字符串。由于是在任意位置插入字符,求最小添加个数问题就可以转化为求正反字符串的最长公共子序列m,总长n-m即为所求。
感性的理解一下,最长公共子序列就是把两个字符串配对好的个数给记录出来,那么没配对的就是需要添加的个数。
由于数据量的问题,5000*5000内存就爆了。所以我们在这里采用滚动数组。
参考代码:
#include<stdio.h>
#include<string.h> 
#define max(a,b) a>b?a:b
int len[2][5005];
int main()
{
	int t,num,m,n,now,pre;
	char str1[5005],str2[5005];
	while(~scanf("%d",&t))
	{
		num=0; 
		memset(len,0,sizeof(len));
		scanf("%s",str1);
		for(int i=0;i<t;i++)
		   str2[t-i-1]=str1[i];
        int len1=strlen(str1);
        for(m=1;m<=len1;m++)
		{
			for(n=1;n<=len1;n++)
			{
				now=m%2;
				pre=1-now;
				if(str1[m-1]==str2[n-1])
			        len[now][n]=len[pre][n-1]+1;
                else 
                    len[now][n]=max(len[now][n-1],len[pre][n]);
			}
			
		}
        printf("%d\n",t-len[len1%2][len1]);
	}
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值