具体解释点击
下面仅为自写代码
一、朴素做法
import java.util.*;
public class Main {
static int n, ans = 0;
static String str;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
n = str.length();
for (int i = 0; i < n; i++) {
int l = i, r = i;
up(i, i);
}
for (int i = 1; i < n; i++) {
if (str.charAt(i) == str.charAt(i - 1)) {
up(i - 1, i);
}
}
System.out.println(ans);
}
static void up(int l, int r) {
while (check(l, r)) {
l--;
r++;
}
if (l < 0 || r >= n) {
l ++;
r --;
}
if (l >= 0 && r < n && str.charAt(l) != str.charAt(r)) {
l ++;
r --;
}
ans = Math.max(ans, r - l + 1);
}
static boolean check(int l, int r) {
return l >= 0 && r < n && str.charAt(l) == str.charAt(r);
}
}
二、字符串哈希与二分
import java.util.*;
public class Main {
static final int N = 1010, p = 131, mod = 998244353;
static long[] pre_h = new long[N], suf_h = new long[N], exp = new long[N];
static int n, ans = 1;
static String str;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
str = " " + sc.nextLine();
n = str.length() - 1;
exp[0] = 1;
for (int i = 1; i <= n; i++) {
exp[i] = exp[i - 1] * p % mod;
pre_h[i] = (pre_h[i - 1] * p + str.charAt(i)) % mod;
}
for (int i = n; i > 0; i--) {
suf_h[i] = (suf_h[i + 1] * p + str.charAt(i)) % mod;
}
for (int i = 1; i <= n - 1; i++) {
int l = 0, r = Math.min(i - 1, n - i);//半径
while (l < r) {
int mid = l + r + 1>> 1;
if (check(i - mid, i - 1, i + 1, i + mid)) l = mid;
else r = mid - 1;
}
ans = Math.max(ans, 2 * l + 1);
}
for (int i = 2; i <= n - 2; i++) {
if (str.charAt(i) == str.charAt(i + 1)) {
int l = 0, r = Math.min(i - 1, n - i - 1);
while (l < r) {
int mid = l + r + 1 >> 1;
if (check(i - mid, i - 1, i + 2, i + mid + 1)) l = mid;
else r = mid - 1;
}
ans = Math.max(ans, 2 * l + 2);
}
}
System.out.println(ans);
}
static boolean check(int l1, int r1, int l2, int r2) {
long h1 = getMod(pre_h[r1] - pre_h[l1 - 1] * exp[r1 - l1 + 1]);
long h2 = getMod(suf_h[l2] - suf_h[r2 + 1] * exp[r2 - l2 + 1]);
return h1 == h2;
}
static long getMod(long u) {
return (u % mod + mod) % mod;
}
}