/**
* Manacher算法
* <p>
* 又叫“马拉车”算法,可以在时间复杂度为O(n)的情况下求解一个字符串的最长回文子串长度的问题
*/
public class Manacher {
public static int manacher(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] arr = manacherString(s);
int[] result = new int[arr.length];
int max = Integer.MIN_VALUE;
int r = -1;
int c = -1;
for (int i = 0; i < arr.length; i++) {
result[i] = r > i ? Math.min(result[2 * c - i], r - i) : 1;
while (i - result[i] > -1 && i + result[i] < arr.length) {
if (arr[i - result[i]] == arr[i + result[i]]) {
result[i]++;
} else {
break;
}
}
if (i + result[i] > r) {
r = i + result[i];
c = i;
}
max = Math.max(max, result[i]);
}
return max - 1;
}
private static char[] manacherString(String s) {
char[] chars = s.toCharArray();
char[] res = new char[2 * chars.length + 1];
for (int i = 0; i != res.length; i++) {
res[i] = (i & 1) == 0 ? '#' : chars[i >> 1];
}
return res;
}
public static void main(String[] args) {
System.out.println(manacher("abc1234321cbs"));
}
}
/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */