思路:
将字符串位置0存入一个-1空出来。
//这里是因为我准备列举回文子串的中心点。并判断其两端的点是否相等。而-1(或这说255)是一个很难出现的字符。
让字符串从1开始存入。
然后依次列举中心点。
//这里需要注意一个问题就是回文子串的长度。考虑到回文子串可能是偶数长度,而偶数长度的回文子串的最中心的有又相同的。所以加入了while (p[e + 1] == p[i]) ++e; 来兼顾偶数长度的回文子串。
根据中心点向两边延生。找到以其中心的回文子串的长度。与当前求得的最长长度比较,取舍。
#include <cstdio>
#include <cstring>using namespace std;
char str[1000002 + 1200];
int fast(char *p)
{
int ans = 1;
for (int i = 1; p[i]; ++i)
{
int s = i, e = i, t;
while (p[e + 1] == p[i]) ++e; //同时兼顾了偶数长度的回文子串
i = e;
while (p[s - 1] == p[e + 1]) --s, ++e;
if ((t = e - s + 1) > ans) ans = t;
}
return ans;
}
int main()
{
str[0]=-1;
int n;
scanf("%d", &n);
while (n --) {
scanf("%s", str + 1);
printf("%d\n", fast(str));
}
return 0;
}