题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
public class Solution {
public int getLongestPalindrome(String A, int n) {
// write code here
if(A == null){
return 0;
}
if(A.length() <= 1){
return A.length();
}
char[] data = A.toCharArray();
int right = 0,left = 0;
boolean[][] dp = new boolean[data.length][data.length];
//注意遍历不要从 0 到 n-1 ,要从尾到头,需要确保遍历中间的那部分是否有回文都判断过
for(int i = n-2;i>=0;i--){
dp[i][i] = true;
for(int j = i+1;j< data.length;j++){
//如何才是回文
if(data[i] == data[j] && ((j - i) < 3 || (i< n && dp[i+1][j-1]))){
dp[i][j] = true;
}
//满足条件
if(dp[i][j] && (right - left) < (j - i)){
left = i;
right = j;
}
}
}
return right - left +1;
}
}