马拉车算法(Manacher算法求最长回文子串)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baodream/article/details/81945533

模板:

const int N = 110005;
char str[N],s[N*2];
int p[N*2],len1,len2;  //p[i]表示以t[i]字符为中心的回文子串的半径

/*s[i]: # 1 # 2 # 2 # 1 # 2 # 2 #
p[i]:     1 2 1 2 5 2 1 6 1 2 3 2 1*/

init(){
    s[0] = '$';  //这里是一个用不大的字符
    s[1] = '#';
    len1 = strlen(str);
    for(int i=0;i<len1;i++){
        s[i*2+2] = str[i];
        s[i*2+3] = '#';
    }
    len2 = len1*2+2;
    s[len2] = '@';  //另一个不会出现的字符,与str[0]不同,防止匹配越界
}

void Manacher(){
    init();         //字符串翻倍
    int id = 0, mx = 0;
    int ans = 0;   //得到最长回文长度
    for(int i = 1;i < len2;i++){
        if(mx > i)
            p[i] = min(p[2*id-i],mx-i);
        else
            p[i] = 1;
        while(s[i+p[i]] == s[i-p[i]]) p[i]++;
        if(mx < p[i]+i){
            id = i;
            mx = p[i]+i;
        }
        ans = max(ans,p[i]-1);  //减1才是最后答案
    }
    printf("%d\n",ans);
}

猜你喜欢

转载自blog.csdn.net/baodream/article/details/81945533