求最长的回文子串的长度。
可以用哈希O(1)的判断左右两边是否对称。
O(N)的枚举每个点,倍增地向两边扩展,扩展的最大长度就是最长的回文子串的长度。
回文串分奇偶,分类讨论就好了
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1000000 + 5;
typedef unsigned long long ull;
ull f[N], p[N], g[N];
string s;
int len;
bool ck1(int pos, int t, int k)
{
if (pos - t - k < 1 || pos + t + k > len) return 0;
int x1 = pos - t - k, y1 = pos - 1;
int x2 = pos + 1, y2 = pos + t + k;
int h1 = f[y1] - f[x1 - 1] * p[y1 - x1 + 1];
int h2 = g[x2] - g[y2 + 1] * p[y2 - x2 + 1];
return h1 == h2;
}
bool ck2(int pos, int t, int k)
{
if (pos - t - k < 0 || pos + t + k > len) return 0;
int x1 = pos - t - k + 1, y1 = pos;
int x2 = pos + 1, y2 = pos + t + k;
int h1 = f[y1] - f[x1 - 1] * p[y1 - x1 + 1];
int h2 = g[x2] - g[y2 + 1] * p[y2 - x2 + 1];
return h1 == h2;
}
int main()
{
int cnt = 0;
while(cin >> s) {
if (s == "END") break;
len = s.length();
s = " " + s;
p[0] = 1;
for (int i = 1; i <= len; i++) {
f[i] = f[i - 1] * 131 + s[i];
p[i] = p[i - 1] * 131;
}
for (int i = len; i >= 1; i--) g[i] = g[i + 1] * 131 + s[i];
int ans1 = 0, ans2 = 0;
for (int i = 1; i <= len; i++) {
int t = 1, k = 0;
while(t) {
if (ck1(i, t, k)) {
k += t;
t *= 2;
}
else t /= 2;
}
ans1 = max(ans1, 2 * k + 1);
int t1 = 1, k1 = 0;
while(t1) {
if (ck2(i, t1, k1)) {
k1 += t1;
t1 *= 2;
}
else t1 /= 2;
}
ans2 = max(ans2, 2 * k1);
}
printf("Case %d: %d\n", ++cnt, max(ans1, ans2));
}
return 0;
}