Light oj--1258(KMP的变形)

Description

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


解体思路:其实该题可以理解成找一个以最后一个元素为结尾的最长回文字符串。可以将输入的字符串逆置,求出它的next数组,然后和kmp,求出重叠部分k。所需要加的字符长度等于l-k。


代码如下:

#include<stdio.h>
#include<string.h>
char s1[1000000+10];
char s2[1000000+10];
int p2[1000000+10];
void get_p(int l){
	int i,j;
	i=0;j=-1;
	p2[0]=-1;
	while(i<l){
		if(j==-1||s2[i]==s2[j]){
			i++;j++;
			p2[i]=j;
		}
		else j=p2[j];
	}
}
int set(int l){
	int i,j;
	i=j=0;
	while(i<l){
		if(j==-1||s1[i]==s2[j]){
			i++;
			j++;
		}
		else j=p2[j];
	}
	return j;
}
int main(){
	int t,cas;
	cas=1;
    scanf("%d",&t);
	while(t--){
		scanf("%s",s1);
		memset(p2,0,sizeof(p2));
		int l;
		l=strlen(s1);
		int j=0;
		for(int i=l-1;i>=0;i--){
			s2[j++]=s1[i];
		}
		get_p(l);
		int k=set(l);
		printf("Case %d: %d\n",cas++,l+l-k);
	}	
	return 0;
}


你可能感兴趣的:(Light oj--1258(KMP的变形))