寻找回文子串,我们可以从某个index开始,向左边,右边扩展
当s[index - 1] == s[index + 1] 的时候,可以继续扩展下去。
注意:我们现在只考虑了奇数长度的回文序列的情况。
它也可能是"bb"这种偶数的回文序列。
所以我们要考虑s[index] == s[index + 1],如果可以,再向两边扩展。
代码:
public class LongestPalindromicSubstring {
private int leftIndex = -1;
private int rightIndex = -1;
private int maxLength = 0;
public String longestPalindrome(String s) {
for (int i = 0; i < s.length(); i++) {
expandPalindrome(s, i, i); //odd
expandPalindrome(s, i, i + 1); //even
}
return s.substring(leftIndex, rightIndex);
}
private void expandPalindrome(String s, int curLeft, int curRight) {
while (curLeft >= 0 && curRight < s.length() && s.charAt(curLeft) == s.charAt(curRight)) {
curLeft--;
curRight++;
}
if (curRight - curLeft - 1 > maxLength) {
maxLength = curRight - curLeft - 1;
leftIndex = curLeft + 1;
rightIndex = curRight;
}
}
}