最长回文子串 Manacher算法

今天看到一个求最大回文子串的算法,可以达到O(N)的时间复杂度和空间复杂度,非常的神奇
先记录一下,有时间一定要写个详细的博客
这篇博客写的很明白,强推
https://articles.leetcode.com/longest-palindromic-substring-part-ii/

#include <iostream>
#include<string.h>
using namespace std;
//manacher's algorithm O(N) O(N)
string preProcess(string s){
    int n=s.length();
    if(n==0) return "$@";
    string res="$";
    for(int i=0;i<n;i++){
        res+="#"+s.substr(i,1);
    }
    res+="#@";
    cout<<res<<endl;
    return res;
}
string longestPlindrome(string str){
    string T=preProcess(str);
    int n=T.length();
    int *p=new int[n];
    memset(p,0,sizeof(p));
    int C=0,R=0;
    for(int i=0;i<n;i++){
        int j=2*C-i;
        //长回文中的中心两边对称,但是不能超出去 
        if(R>i){
            p[i]=p[j]<R-i?p[j]:R-i;
        }else{
            p[i]=0;
        }
        //针对超出去的情况,继续探查两边 
        while(T[i+p[i]+1]==T[i-p[i]-1]){
            p[i]++;
        }
        //更新C和R 
        if(i+p[i]>R){
            R=i+p[i];
            C=i;
        }
    }
    //获取最大回文串 
    int maxLen=0,maxIndex=0;
    for(int i=0;i<n;i++){
        if(p[i]>maxLen){
            maxLen=p[i];
            maxIndex=i;
        }
    }
    return str.substr((maxIndex-maxLen-1)/2,maxLen);
}
int main() {
    cout<<longestPlindrome("abcabac")<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/armstrong_rose/article/details/80473071