最长回文串O(N)算法 manacher

// 原串最大长度N
// 返回最大回文字串 res
#include<cstdio> #include<cstring> #include<cstdlib> #include<string> #include<algorithm> using namespace std; const int N = 1024; int rid[N<<2]; string manacher(char *s){ string t, res; int L = strlen(s); // init t += '?'; for(int i = 0; i < L; i++) t += '#', t += s[i]; t += "#*"; // getrid for(int i=1,j=0,k,End=(int)t.size();i<End;){ while( t[i-j-1]==t[i+j+1] ) j++; rid[i] = j; for(k=1;k<=j&&(rid[i-k]!=rid[i]-k);k++) rid[i+k] = min( rid[i-k], rid[i]-k ); i += k; j = max( 0,j-k ); } // Max int m = 0, pos; for(int i = 1; i < (int)t.size(); i++){ if( m < rid[i]*2+(t[i]!='#') ) m = rid[i]*2+(t[i]!='#'), pos = i; } for(int i = pos-rid[pos]; i <= pos+rid[pos]; i++){ if( t[i] != '#' ) res += t[i]; } return res; } int main(){ char s[N]; scanf("%s", s); string ans = manacher(s); // printf("MaxLength = %d\n", ans.size() ); printf("%s\n", ans.c_str() ); return 0; }

 

你可能感兴趣的:(man)