4.C++实现Manacher算法模板

其他经典算法:https://blog.csdn.net/qq_41562704/article/details/86441022

最终结果result保存的的是最长回文串

string s;//原字符串
string temp;//原字符串插入特殊字符
string result,tempresult;//最终结果子字符串
//形成temp字符串
void INIT(string s){
    int len=s.length();
    temp+='@';
    for(int i=0;i<len;i++){
        temp+='#';
        temp+=s[i];
    }
    temp+="#$0";
}
//核心算法
void Manacher(string s){
    int len=s.length();
    std::vector<int> Len(len,0);
    int mx=0,ans=0,po=0;
    for(int i=0;i<len;i++){
        Len[i]=mx>i? min(mx-i,Len[2*po-i]) : 1;
        while(s[i-Len[i]]==s[i+Len[i]])
            Len[i]++;
        if(Len[i]+i>mx){
            mx=Len[i]+i;
            po=i;
        }
        if(Len[i]>ans){
            ans=Len[i];
            tempresult=s.substr(i-Len[i]+1,2*Len-1);
        }
    }
}
int main(){
    INIT(s);
    Manacher(s);
    for(int i=0;i<tempresult.length();i++)
        if(tempresult[i]!='#')
            result+=tempresult[i];
}

猜你喜欢

转载自blog.csdn.net/qq_41562704/article/details/86476954