注意:
区别于判断一个串是否为回文串,本题是求最长回文子串!
方法一、动态规划
1、状态定义:dp[i][j],串i到j表示回文子串的长度;
2、状态方程:
dp[i][j] = dp[i+1][j-1] + 2, s[i] = s[j];
dp[i][j] = dp[i+1][j-1], s[i] != s[j];
3、初始值:
dp[i][i] = 1;
方法二、逐个中心扩散
遍历元素,对每一个元素进行中心扩散,记住最大长度;
public String longestPalindrome(String s) {
int len = 0,st=0,end=0;
for(int i=0;i<s.length();i++){
int len1=expandAroundCenter(s,i,i);
int len2=expandAroundCenter(s,i,i+1);
len = Math.max(len1,len2);
if(len > end - st){
st = i-(len-1)/2;// 0 - 1 = -1
end = i+len/2;
}
}
return s.substring(st,end+1);
}
public int expandAroundCenter(String s,int left, int right){
int i = left,j = right;
while(i>=0 && j<s.length() && s.charAt(i)==s.charAt(j)){
i--;j++;
}
return j-i-1;
}