/*算法功能:奇数串最长回文串长度-Manacher算法(马拉车算法)
思路:1.转换原始串字符个数为奇数个(2n+1个):int INIT(char *st)
2.计算所有字符的回文半径(mx-前面计算回文串最右位置,po-最右位置对应中心下标);
3.最长回文长度=max(回文半径)-1
调用:scanf("%s",str); int len = INIT(str);
printf("%d\n",MANACHER(tmp,len));
@param:char *st-转换后字符数组,len-为转换后的字符数组长度
*/
#include<bits/stdc++.h>
using namespace std;
const int maxn=1000010;
char str[maxn];//原字符串
char tmp[maxn<<1];//转换后的字符串
int Len[maxn<<1];
//转换原始串字符个数为奇数个(2n+1个)
//转换st[n]为tem[2n+1]
int INIT(char *st)
{
int i,len=strlen(st);
tmp[0]='@';//字符串开头增加一个特殊字符,防止越界
for(i=1;i<=2*len;i+=2)
{
tmp[i]='#';
tmp[i+1]=st[i/2];
}
tmp[2*len+1]='#';
tmp[2*len+2]='$';//字符串结尾加一个字符,防止越界
// tmp[2*len+3]=0;
return 2*len+1;//返回转换字符串的长度
}
int MANACHER(char *st,int len)
{//mx-前面计算回文串最右位置,po-最右位置对应中心下标,ans=最长回文长度+1
int mx=0,ans=0,po=0;
for(int i=1;i<=len;i++)
{
if(mx>i)//mx>i时(通过i关于po的对称点确定j的回文半径)
Len[i]=min(mx-i,Len[2*po-i]);//注意:i>=po,因为po为前面位置下标
else
Len[i]=1;//默认Len[i]最小值=1;
while(st[i-Len[i]]==st[i+Len[i]])Len[i]++;
if(Len[i]+i>mx)//若新计算的回文串右端点位置大于mx,要更新po和mx的值
{
mx=Len[i]+i;
po=i;
}
ans=max(ans,Len[i]);
}
return ans-1;//返回Len[i]中的最大值-1即为原串的最长回文子串额长度
}
int main(){
scanf("%s",str); int len = INIT(str);
printf("%d\n",MANACHER(tmp,len));
return 0;
}
参考网址1:https://blog.csdn.net/dyx404514/article/details/42061017
参考网址2:https://www.felix021.com/blog/read.php?2040