求一个最长回文子串,使用中心探测法,向两边探测即可(当然马拉车算法也可以做)
class Solution {
int max, left, right;
public String longestPalindrome(String s) {
if (s.length() == 0 || s.length() == 1) return s;
for (int i = 0; i < s.length() - 1; i++) {
// 奇偶情况
judge(s, i, i);
judge(s, i, i + 1);
}
return s.substring(left, right);
}
public void judge(String s, int lo, int hi) {
int n = s.length();
while (lo >= 0 && hi < n && s.charAt(lo) == s.charAt(hi)) {
lo--;
hi++;
}
if (hi - lo - 1 > max) {
max = hi - lo - 1;
left = lo + 1;
right = hi;
}
}
}