最长回文字符串 manacher算法

来源:互联网 发布:网络打字员工作 编辑:程序博客网 时间:2024/05/16 17:48
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;const int  N = 1000005;char str[N];char sc[2*N+10];int p[N*2+10];int main(){    int i, len, maxx, ai, k=1;    while(~scanf("%s", str))    {        if(strcmp(str,"END")==0)            break;        len = strlen(str);        sc[0]='$';        for(i=0; i<=len; i++)//注意是等于len,把空字符给了sc的最后一位        {            sc[i*2+1]='#';            sc[i*2+2]=str[i];        }        int ans = 0;        ai=0;        maxx=0;        memset(p,0,sizeof(p));        for(i=1; i<len*2+2; i++)        {            if(maxx>i)                p[i]=min(p[2*ai-i], maxx-i);//这个网上有很多介绍,对称点2*ai-i
//如果超过ai所能到达的最右边的位置也就是maxx-i,最后取其中较小者。            else                p[i]=1;            while(sc[i-p[i]]==sc[i+p[i]])            {                p[i]++;            }            if(maxx<i+p[i])            {                maxx=p[i]+i;                ai=i;            }            if(ans<p[i])            {                ans=p[i];            }        }        printf("Case %d: %d\n", k++ ,ans-1);    }    return 0;}
0 0
原创粉丝点击