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.
思路, dp,用一个二维数组来记录当前下标 i, j,之间是否是palindromic,
如何判断是呢? 首先 i, j 位置的character 必须一样, 然后或者dp[i + 1][j - 1]== true, 或者 j - i <= 2, j - i == 2的时候比如 aba, 中间只隔
着一个元素, 肯定是回文。
reference : http://codeganker.blogspot.com/2014/02/longest-palindromic-substring-leetcode.html
public class Solution {
public String longestPalindrome(String s) {
if(s == null || s.length() == 0)
return "";
int start = 0;
int len = 0;
boolean[][] dp = new boolean[s.length()][s.length()];
for(int i = s.length() - 1; i >= 0 ; i--){
for(int j = i; j < s.length(); j++){
if(i == j){
dp[i][j] = true;
}else{
if(i < s.length() - 1 && j > 0){
dp[i][j] = s.charAt(i) == s.charAt(j) && (dp[i + 1][j - 1] || j - i <= 2);
}
}
// dp[i][j] = s.charAt(i) == s.charAt(j) && (dp[i + 1][j - 1] || j - i <= 2);
//dp[i][j] = s.charAt(i) == s.charAt(j) && ( j - i <= 2 || dp[i + 1][j - 1]);
if(dp[i][j]){
if(j - i + 1 > len){
len = j - i + 1;
start = i;
}
}
}
}
return s.substring(start, start + len);
}
}
上面的代码其实写复杂了,用下面一行就可以完成dp[i][j]的赋值了, 但是要注意先判断是否 j - i <= 2, 如果 或 的操作顺序反过来, “a” 这个test case就过不了。。
dp[i][j] = s.charAt(i) == s.charAt(j) && ( j - i <= 2 || dp[i + 1][j - 1]);