Manacher's Algorithm

马拉车


#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; string Manacher(string s) { string str="$#"; for(int i=0;i<s.size();i++) { str+=s[i]; str+="#"; } // cout<<str<<endl; vector<int> P(str.size(),0); int mi=0,right=0; ///mi为最大回文串对应的中心点,right为该回文串能达到的最右端的值 int maxLen=0,maxPoint=0; ///maxLen为最大回文串的长度,maxPoint为记录中心点 // cout<<str.size()<<endl; for(int i=1;i<str.size();i++) { P[i]=right>i ?min(P[2*mi-i],right-i):1; while(str[i+P[i]]==str[i-P[i]]) P[i]++; ///一步步匹配 if(right<i+P[i]) { ///超过之前的最右端,则改变中心点和对应的最右端 right=i+P[i]; mi=i; } ///更新最大回文串的长度,并记下此时的点 if(maxLen<P[i]) { maxLen=P[i]; maxPoint=i; } // cout<<P[i]<<" "; } // cout<<endl; return s.substr((maxPoint-maxLen)/2,maxLen-1); } int main( ) { string s; cin>>s; cout<<Manacher(s)<<endl; return 0; } /// cabbaf

猜你喜欢

转载自www.cnblogs.com/wile/p/11784528.html
今日推荐