您的位置:首页 > 其它

5. Longest Palindromic Substring

2016-07-15 10:36 211 查看
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.

方法1:

DP找出[a,b]是否是回文串,在这个过程中,可以记录最大的回文串,O(N^2)

public static String longestPalindrome(String s)
{
int len=s.length();
if(len<1)
return "";
boolean[][] dp=new boolean[len][len];
int indexi=0,indexj=0,max=Integer.MIN_VALUE;
for(int i=len-1;i>=0;i--)
for(int j=0;j<len;j++)
{
if(i>=j)
dp[i][j]=true;
else {
dp[i][j]=dp[i+1][j-1]&&(s.charAt(i)==s.charAt(j));
if(dp[i][j])
if(Math.abs(i-j)>max)
{
max=Math.abs(i-j);
indexi=i;
indexj=j;
}
}
}
return s.substring(indexi, indexj+1);
}


方法2:

逐个字符扫描,看以当前字符是否能够扩展形成的回文串最长是多长,因为回文串的对称中心有可能是一个字符,有可能是一个位置,

所以尝试扩展的时候要分情况,形成奇串和偶串的处理稍有不同。最坏情况O(N^2)

public static String longestPalindrome(String str)
{
if (str.isEmpty())
return null;
int[] odd, even;
int max = 0, a = 0, b = 0;
for (int i = 0; i < str.length(); i++)
{
odd = expandPalindrome(str, i - 1, i + 1);
if (odd[1] - odd[0] > max)
{
a = odd[0];
b = odd[1];
max = b - a;
}
even = expandPalindrome(str, i, i + 1);
if (even[1] - even[0] > max)
{
a = even[0];
b = even[1];
max = b - a;
}
}

return str.substring(a, b);
}

private static int[] expandPalindrome(String str, int a, int b)
{
while (a >= 0 && b < str.length() && str.charAt(a) == str.charAt(b))
{
a--;
b++;
}
return new int[]{a + 1,b};
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: