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
分析:
这道题就是给出一串字符,然后把它变成回文串后的总长度。
先把字符串倒转,然后用kmp求出其中连续相同的字母的个数,然后用此字符串长度的二倍减去相同的字母的个数,就是这串字母的最短回文串。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<iostream>
using namespace std;
const int maxn=1000010;
char s1[maxn],s2[maxn];
int next[maxn];
int len;
int t;
void getfail()
{
int i=0,j=-1;
next[0]=-1;
while(i<len)
{
if(j==-1||s2[i]==s2[j])
{
i++,j++;
next[i]=j;
}
else j=next[j];
}
}
void kmp()
{
getfail();
int i=0,j=0;
while(i<len)
{
if(j==-1||s1[i]==s2[j])
{
i++,j++;
}
else j=next[j];
}
printf("%d\n",len*2-j);
}
int main(){
scanf("%d",&t);
int cnt=0;
while(t--)
{
//getchar();
scanf("%s",s1);
//getchar();
len=strlen(s1);
printf("Case %d: ",++cnt);
reverse_copy(s1,s1+len,s2);
s2[len]=0;
kmp();
}
return 0;
}