题目链接:http://www.lightoj.com/volume_showproblem.php?problem=1258
题意:为了使原串变为回文串,可任意添加字符,求变为回文串之后字符的长度。
解法:求字符串与其反串的最大公共长度len,则最后回文字符串的长度为:原串长度*2-len;
代码:
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <algorithm>
#include <vector>
#include <string.h>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <sstream>
#include <time.h>
#include <malloc.h>
using namespace std;
#define LL long long
void get_next(char x[], LL m, LL Next[])
{
LL i, j;
j = Next[0] = -1;
i = 0;
while (i < m)
{
while (-1 != j && x[i] != x[j]) j = Next[j];
Next[++i] = ++j;
}
}
LL Next[1001000];
long long KMP(char x[], LL m, char y[], LL n)//x模式串 y主串
{
LL i, j, ans = 0;
i = j = 0;
get_next(x, m, Next);
while (i < m && j < n)
{
if (j ==-1 || x[j] == y[i])
{
i++;
j++;
}
else
j = Next[j];
}
return n + m - j;
}
char a[1000100], b[1000100];
int main()
{
LL t;
scanf("%lld",&t);
for (LL i = 1; i <= t;i++)
{
scanf("%s", a);
LL n = strlen(a);
for (LL k = 0; k < n; k++)
b[n - k -1] = a[k];
long long tmp = KMP(b, n, a, n);
printf("Case %lld: ",i);
printf("%lld\n",tmp);
}
}