题目链接:http://hihocoder.com/problemset/problem/1032
推荐讲解博客:https://segmentfault.com/a/1190000003914228
#include <iostream> #include <string> #include <cstring> #define MAX_N 2000005 using namespace std; int RL[MAX_N]; // RL[i] : 以i为中心的回文半径的值 void convert( string& str ) { string newstr = "#"; for ( int i = 0, len = str.size() ; i < len ; ++ i ) { newstr += str[i]; newstr += "#"; } str = newstr; } int main() { int n; string str, nstr; cin >> n; while ( n -- ) { memset( RL, 0, sizeof(RL) ); cin >> str; // 统一处理插入了特殊字符 convert(str); // cout << str << endl; int MaxRight = 0; int pos = 0; int MaxLen = 0; for ( int i = 0, len = str.size() ; i < len ; ++ i ) { // 防止重复匹配 if ( i < MaxRight ) { RL[i] = min(RL[2*pos-i], MaxRight-i); } else { RL[i] = 1; } // 尝试扩展 注意边界 防止越界 while ( i-RL[i]>=0 && i+RL[i]<=len && str[i-RL[i]]==str[i+RL[i]] ) RL[i] ++; if ( RL[i]+i-1 > MaxRight ) { MaxRight = RL[i]+i-1; pos = i; } // 更新结果 if ( MaxLen < RL[i] ) MaxLen = RL[i]; } cout << MaxLen-1 << endl; } return 0; }