一,题目
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,j == i true
2,j+1 == i s[j] == s[i]
3,否则
s[j+1][i-1] && s[j]==s[i]
三,代码如下
public String longestPalindrome(String s) {
if(s == null || s.length() == 1){
return s;
}
char[] chs = s.toCharArray();
int len = s.length();
int max = 0;
int start = 0,end = 0;
boolean[][] memo = new boolean[len][len];
/*
*1,j == i true
*2,j+1 == i s[j] == s[i]
*3,否则
* s[j+1][i-1] && s[j]==s[i]
*/
for(int i=0; i<len;i++){
for(int j=0; j<=i; j++){
if(j == i){
memo[j][i] = true;
}else if((j+1) == i){
memo[j][i] = (chs[j] == chs[i]);
}else {
memo[j][i] = (memo[j+1][i-1] && (chs[j] == chs[i]));
}
if(!memo[j][i]){
continue;
}
if(i-j +1 > max){
max = i-j+1;
start = j;
end = i;
}
}
}
return s.substring(start, end+1);
}