最长回文子串
回文,亦称回环,是正读反读都能一样的字符串。例如“12321”、“abba”等。
现在给你一个字符串,请你找出其中长度最长的回文。
import java.util.Scanner;
public class Main {
private static char[] getMatcher(String str) {
char[] ret = new char[str.length() << 1 | 1];
for (int i = 0; i < str.length(); ++i) {
ret[i << 1] = '#';
ret[i << 1 | 1] = str.charAt(i);
}
ret[ret.length - 1] = '#';
return ret;
}
private static String solve(String str) {
if (str == null || str.length() == 0) {
return "";
}
char[] matcher = getMatcher(str);
int c = -1, r = -1, max = 0, maxIndex = -1;
int[] p = new int[matcher.length];
for (int i = 0; i < matcher.length; ++i) {
// 0 1 2 3
p[i] = i > r ? 1 : Math.min(r - i + 1, p[2 * c - i]);
while (i + p[i] < matcher.length && i - p[i] >= 0) {
if (matcher[i + p[i]] == matcher[i - p[i]]) {
p[i]++;
} else {
break;
}
}
if (i + p[i] - 1 > r) {
r = i + p[i] - 1;
c = i;
}
if (p[i] > max) {
max = p[i];
maxIndex = i;
}
}
// #a#b#a#
// #a#a#
int start = (maxIndex - max + 1) >> 1, end = start + max - 1;
return str.substring(start, end);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(solve(in.next()));
}
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号