Manacher

Manachers算法是一个可求字符串的最长回文穿的高效率算法

优点:速度高

这是一篇清晰移动的博客:传送

代码实现:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int N=2e5;
 5 
 6 string Mnc(string &s)
 7 {
 8     string t="$#";
 9     for(int i=0;i<s.length();++i)//構造輔助串
10     {
11         t+=s[i];
12         t+='#';
13     }
14 
15     int ml=0,p=0,R=0,M=0;
16     //最大長度,最長迴文中心,當前最大迴文串右端,當前最長迴文中心
17     
18     int len=t.length();
19     vector<int> P(len,0);//迴文長度數組
20     for(int i=0;i<len;++i)
21     {
22         P[i]=R>i?min(P[2*M-i],R-i):1;//轉移方程
23         
24         while(t[i+P[i]]==t[i-P[i]])//長度擴張
25             ++P[i];
26 
27         if(i+P[i]>R)//更新右端和中心
28         {
29             R=i+P[i];
30             M=i;
31         }
32         if(ml<P[i])//記錄極大
33         {
34             ml=P[i];
35             p=i;
36         }
37     }
38 
39     return s.substr((p-ml)/2,ml-1);//返回迴文串
40 }
41 
42 int main()
43 {
44     string a;
45     while(cin>>a)
46         cout<<Mnc(a)<<endl;
47 }
原文地址:https://www.cnblogs.com/Lin88/p/10073985.html