最長迴文子串 Manacher演算法
阿新 • • 發佈:2019-02-18
#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;
}