Central Expansion method
the main idea is Expanding from the center point of the Palindrome:
We should iterate every center potion of possible Palindrome in the String. There are 2n - 1 points that maybe the center of a Palindrome(why it is 2n - 1 instead of n: excepet of the occasion that a element within the string is the center a Palindrom, there’s another ocaasion that when the Palindrome contains an even number of characters, The center of the Palindrome would be the gap within two elements, but not an element.
public static String longestPalindrome(String s) {
int len1, len2, len, start, end;
start = 0;
end = 0;
for (int i = 0; i < s.length(); i++) {
len1 = expandFromCenter(s, i, i);
len2 = expandFromCenter(s, i, i + 1);
len = Math.max(len1, len2);
if(len > end - start)//the newest Palindrome is longer or equal than the last longest Palindrome
{
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
public static int expandFromCenter(String s, int L, int R) {
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;//R - L + 1 - 2
}
what bug I’ve made
- I’ve made a stupid mistake that is I missed a pair of {} for a if statement(this is really really stupid and comsumed much energy of mine)