描述
找出字符串中的最长回文字串
解决
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int manacher(string str);
int cnt[2000005];
int main()
{
int t;
cin >> t;
while (t--)
{
string str;
cin >> str;
//cout << "zz" << endl;
cout << manacher(str) << endl;
}
return 0;
}
int manacher(string str)
{
string res;
int length = str.size();
res.resize(length * 2 + 2);
res[0] = '$', res[1] = '#';
for (int i = 0; i < length; ++i)
{
res[(i + 1) << 1] =str[i];
res[((i + 1) << 1) + 1] = '#';
}
int id = 0, mx = 0;
length = res.size();
//cout << length << endl;
memset(cnt, 0, sizeof(cnt));
//cout << res << endl;
for (int i = 1; i < length - 1; ++i)
{
cnt[i] = mx > i ? min(cnt[2 * id - i], mx - i) : 1;
while (res[i + cnt[i]] == res[i - cnt[i]])
++cnt[i];
//cout << "here " << cnt[i] << endl;
if (cnt[i] + i > mx)
{
mx = cnt[i] + i;
id = i;
}
}
int max_length = 0;
//cout << "-----\n";
for (int i = 0; i < length - 1; ++i)
{
//cout << cnt[i] << endl;
if (cnt[i] > max_length)
max_length = cnt[i];
}
//cout << "-0------\n";
//cout << max_length << endl;
//getchar();
return max_length - 1;
}