题目
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
分析
大牛给出了5种解法:
http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html
http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
重点是第五种:Manacher,O(n)的时间复杂度,具体分析看大牛的解释,英文看不懂的话,文章里还给了一篇中文的链接
解答
public class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
int N = s.length();
int M = 2 * N + 3;
char[] c = new char[M];
c[0] = '$';
for (int i = 0; i < N; ++i) {
c[i * 2 + 1] = '#';
c[i * 2 + 2] = s.charAt(i);
}
c[M - 2] = '#';
c[M - 1] = '*';
int mx = 0;
int id = 0;
int[] p = new int[M];
for (int i = 1; i < M - 1; ++i) {
if (mx > i) {
p[i] = Math.min(p[2 * id - i], mx - i);
}
while (c[i + p[i]] == c[i - p[i]]) {
++p[i];
}
if (i + p[i] > mx) {
mx = i + p[i];
id = i;
}
}
int max = 0;
int mid = 0;
for (int i = 1; i < M - 1; ++i) {
if (p[i] > max) {
max = p[i];
mid = i;
}
}
return new String(c).substring(mid - p[mid] + 2, mid + p[mid] - 1)
.replaceAll("#", "");
}
}