import java.util.Scanner;
public class TheLengthPalindromicNumber1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while (n-- != 0) {
String a = in.next();
int len = a.length();
int nlen = 2 * len + 3;
char b[] = new char[nlen + 10];
char c[] = a.toCharArray();
int max = 0;
int id = 0;
b[0] = '$';
b[1] = '#';
int i = 0;
for (; i < len; i++) {
b[i * 2 + 2] = c[i];
b[i * 2 + 3] = '#';
}
b[nlen - 1] = 0;
int p[] = new int[nlen];
for (int j = 1; j < nlen; j++) {
p[j] = 0;
}
for (i = 1; i < nlen; i++) {
if (max > i)
p[i] = Math.min(p[2 * id - i], p[id] + id - i);//那个比较小,那个才是真的
else
p[i] = 1;
while (b[i + p[i]] == b[i - p[i]])
p[i]++;
if (p[i] + i > max) {
max = p[i] + i;
id = i;
}
}
int mx = 0;
for (i = 1; i < nlen; i++) {
if (mx < p[i] - 1)
mx = p[i] - 1;
}
System.out.println(mx);
}
in.close();
}
}
最长回文子串优化
最新推荐文章于 2022-04-14 21:51:40 发布