Making Huge Palindromes (回文串,kmp)

题目链接:https://vjudge.net/problem/LightOJ-1258

A string is said to be a palindrome if it remains same when read backwards. So, 'abba', 'madam' both are palindromes, but 'adam' is not.

Now you are given a non-empty string S, containing only lowercase English letters. The given string may or may not be palindrome. Your task is to make it a palindrome. But you are only allowed to add characters at the right side of the string. And of course you can add any character you want, but the resulting string has to be a palindrome, and the length of the palindrome should be as small as possible.

For example, the string is 'bababa'. You can make many palindromes including

bababababab

babababab

bababab

Since we want a palindrome with minimum length, the solution is 'bababab' cause its length is minimum.

Input

Input starts with an integer T (≤ 10), denoting the number of test cases.

Each case starts with a line containing a string S. You can assume that 1 ≤ length(S) ≤ 106.

Output

For each case, print the case number and the length of the shortest palindrome you can make with S.

Sample Input

4

bababababa

pqrs

madamimadam

anncbaaababaaa

Sample Output

Case 1: 11

Case 2: 7

Case 3: 11

Case 4: 19

Note

Dataset is huge, use faster I/O methods.

题意:给出一个字符串,可以在字符串后面增加字符将其变为回文串。问最少增加几个字符原串能变为回文串,输出变为回文串后的字符串的最小长度。

题解 :将原串与逆序串相互匹配,求出他们的最长的相同长度ans,所以要增加的长度就是len-ans,所以变为回文串后的字符串的最小长度为len+len-ans,即2*len-ans

例如:原串: ababb       逆序串:bbaba      将原串的后缀与逆序串的前缀匹配,得到最长相同缀为bb,长度为2,即所求回文串的长度为  2*5-2=8。
 

#include<cstdio>
#include<cstring>
using namespace std;
const int N=1e6+5;
char s[N];
char ss[N];
int next[N];
int len;
void getnext(char s[],int len){
	int j=-1;
	next[0]=-1;
	for(int i=1;i<len;i++){
		while(j!=-1&&s[i]!=s[j+1]) j=next[j];
		if(s[i]==s[j+1]) j++;
		next[i]=j;
	}
}
int kmp(char text[],char pattern[]){
	int n=strlen(text),m=strlen(pattern);
	getnext(pattern,len);
	int j=-1;
	for(int i=0;i<n;i++){
		while(j!=-1&&text[i]!=pattern[j+1]) j=next[j];
		if(text[i]==pattern[j+1]) j++;
	}
	return j+1;
}
int main(){
	int T;
	scanf("%d",&T);
	for(int k=1;k<=T;k++){
		scanf("%s",s);
		len=strlen(s);
		for(int i=0;i<len;i++){
			ss[i]=s[len-1-i];
		}
		int ans=kmp(s,ss);
		printf("Case %d: %d\n",k,2*len-ans);
	}
	return 0;
}

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值