思路:采用动态规划来做,dp[i][j]表示s中下标i到下标j能否构成回文,递推公式为:
dp[i, j] = 1 if i == j
= s[i] == s[j] if j = i + 1
= s[i] == s[j] && dp[i + 1][j - 1] if j > i + 1
参考:http://www.cnblogs.com/grandyang/p/4464476.html
代码:
public class LongestPalindromicSubstring5 {
public static void main(String[] args) {
System.out.println(longestPalindrome("babad"));
}
public static String longestPalindrome(String s) {
if(s.length()==0)
return "";
int len = s.length();
boolean dp[][] = new boolean[len][len];
String str = "";
int maxlen = 0;
int left=0,right=0;
for (int i = 0; i < len; i++) {
dp[i][i]=true;
}
//i需要从底往上遍历,因为dp[i+1][j-1],会用到当前i之后的数值
for (int i = len-1; i >=0; i--) {
for (int j = i; j < len; j++) {
if(i==j)
dp[i][j]=true;
else if(j==i+1 && s.charAt(i)==s.charAt(j))
dp[i][j]=true;
else
dp[i][j]=(s.charAt(i)==s.charAt(j))&&dp[i+1][j-1];
if(dp[i][j]&&j+1-i>maxlen)
{
left=i;
right=j;
maxlen = j+1-i;
}
}
}
// for (int i = 0; i < dp.length; i++) {
// for (int j = 0; j < dp.length; j++) {
// System.out.print(dp[i][j]+" ");
// }
// System.out.println();
// }
return s.substring(left,right+1);
}
}
输出:aba
dp时间复杂度O(n2),马拉车算法(Manacher's Algorithm)可以将时间复杂度降为O(n)。