最长回文子串
题目
给出一个字符串(假设长度最长为1000),求出它的最长回文子串,你可以假定只有一个满足条件的最长回文串。
样例
给出字符串 “abcdzdcab”,它的最长回文子串为 “cdzdc”。
挑战
O(n^2) 时间复杂度的算法是可以接受的,如果你能用 O(n) 的算法那自然更好。
题解
Manacher算法,时间复杂度为O(n)。
public class Solution {
/**
* @param s input string
* @return the longest palindromic substring
*/
public String longestPalindrome(String s) {
if (s == null || s.length() == 0)
{
return "";
}
int length = s.length();
int max = 0;
String result = "";
for(int i = 1; i <= 2 * length - 1; i++)
{
int count = 1;
while(i - count >= 0 && i + count <= 2 * length && get(s, i - count) == get(s, i + count))
{
count++;
}
count--;
if(count > max)
{
result = s.substring((i - count) / 2, (i + count) / 2);
max = count;
}
}
return result;
}
private char get(String s, int i)
{
return i % 2 == 0 ? '#' : s.charAt(i / 2);
}
}
Last Update 2016.11.2