Manacher算法用来查找字符串中最大回文子串的长度,具有O(N)的时间复杂度。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Manacher(char* a, int* P)
{
int size = strlen(a);
P[0] = 1;
int id = 0;
int mx = 1;
for(int i=1; i<size; i++)
{
if(mx>i)
P[i] = P[2*id-i]<mx-i?P[2*id-i]:mx-i;
else
P[i] = 1;
for(;a[i-P[i]]==a[i+P[i]] && (i-P[i]>=0);P[i]++);
if(mx<i+P[i])
{
mx = i+P[i];
id = i;
}
}
}
int GetLength(int* P, int size)
{
int i,max=-1;
for(i=0; i<size; i++)
if(max<P[i])
max = P[i];
return max-1;
}
char* ChangeChar(char* a)
{
int size = strlen(a);
char* b = (char*)malloc((2*size+1)*sizeof(char));
b[0] = '#';
for(int i=0; i<size; i++)
{
b[2*i+1] = a[i];
b[2*i+2] = '#';
}
b[2*size+1] = '\0';
return b;
}
int main()