---
Solution: For each index in the string, find the longest palindrome that centers in that index. Note that a palindrome with an odd length and one with an even length have to be checked for separately. Return the longest palindrome ever found.
public class Solution {
public String longestPalindrome(String s) {
if (s.length() <= 1) return s;
int maxLength = 0;
int maxStart = 0;
int maxEnd = 0;
for (int i = 0, last = s.length() - 1; i <= last; i++) {
// Find longest palindrome with odd number of characters.
int start = i;
int end = i;
while (start > 0 && end < last && s.charAt(start - 1) == s.charAt(end + 1)) {
start--;
end++;
}
if (end - start + 1 > maxLength) {
maxLength = end - start + 1;
maxStart = start;
maxEnd = end;
}
// Find longest palindrome with even number of characters.
start = i + 1;
end = i;
while (start > 0 && end < last && s.charAt(start - 1) == s.charAt(end + 1)) {
start--;
end++;
}
if (end - start + 1 > maxLength) {
maxLength = end - start + 1;
maxStart = start;
maxEnd = end;
}
}
return s.substring(maxStart, maxEnd + 1);
}
}
No comments:
Post a Comment