百度:Manacher算法
代码
#include <iostream> #include <string> #include <cstring> #include <algorithm> using namespace std; int MANACHER(const string &str) { string data; int len = str.length(); data+="$#"; for (int i=0;i<len;i++) { data+=str[i]; data+='#'; } data+='@'; //到此预处理完成 len = data.length(); int *temp = new int[len+2]; memset(temp,0,sizeof(temp)); int MaxIndex=0; int i=1,index=0,res=0; for(;i<len;i++) { if (MaxIndex>i) { temp[i]=(MaxIndex-i<temp[2*index-i]?MaxIndex-i:temp[2*index-i]); } else temp[i]=1; while (data[i-temp[i]] == data[i+temp[i]]) { temp[i]++; } if(i+temp[i] > MaxIndex) { MaxIndex = i+temp[i]; index=i; } res = (res>temp[i]?res:temp[i]); } delete[]temp; return res-1; } int main() { string str ; int n; while(cin >> n) { while (n--) { cin >> str; cout << MANACHER(str)<<endl; } } return 0; }