Manacher 入门+模板 回文串专用算法

Manacher 算法 回文串专用算法

manacher 应该是一个人的名字。palindrome名词:回文。

博客推荐

https://www.cnblogs.com/lykkk/p/10460087.html,比较简洁,代码清晰。

https://www.cnblogs.com/cloudplankroader/p/10988844.html, 一些细节的东西比较讲解比较细。

模板

//预处理函数,使得处理后的字符串长度为奇数,并且有一些比较好的性质
int init(char* s, char* ss)
{
	int len=strlen(s);
	ss[0]='$'; ss[1]='#';
    int j=2;
	for(int i=0; i<len; i++)
	{
		ss[j++]=s[i];
		ss[j++]='#';	
	}
	ss[j]='\0';
	return j;	
}
//时间复杂度为O(N)
int manacher(char *st, int len)
{
	int mx=0, ans=0, po=0;
	for(int i=1; i<=len; i++)
	{
		if(mx>i)
			p[i]=min(mx-i, p[2*po-i]);
		else 
			p[i]=1;
		while( st[i-p[i] ] == st[ i+p[i] ] ) p[i]++;
		if(p[i]+i > mx)
		{
			mx=p[i]+i;
			po=i;
		}
		ans=max(ans, p[i]);
	}
	return ans-1; //返回的是回文串中的最大长度
}
posted @ 2020-02-01 14:57  ALKING1001  阅读(109)  评论(0编辑  收藏  举报