题:给定一个字符串 s,找到 s 中最长的回文子串
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) {
return "";
}
char[] chars = s.toCharArray();
int start = 0, end = 0;
for (int i = 0, length = chars.length; i < length; i++) {
//验证abba格式的回文
int len1 = expandAroundCenter(chars, i, i);
//验证aba格式的回文
int len2 = expandAroundCenter(chars, i, i + 1);
int max = Math.max(len1, len2);
if (max > end - start) {
//(max - 1)是由于验证aba格式时对i进行了+1操作,并且这里利用了整数相除,直接取整的结果维护i和i+1相等性,至于除以2是因为expandAroundCenter方法的循环内每次l--,
// r++相于对i操作两次,所以除以2
start = i - (max - 1) / 2;
end = i + max / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(char[] chars, int l, int r) {
while (l >= 0 && r < chars.length && chars[l] == chars[r]) {
l--;
r++;
}
return r - l - 1;
}