Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
class Solution {
public String longestPalindrome(String s) {
String res = null;
int maxLength = 0, len = s.length();
for(int i = 0; i < len; i++) {
if(isPalindromic(s, i - maxLength - 1, i)) { // 减少无意义的搜索
res = s.substring(i - maxLength - 1, i + 1);
maxLength += 1;
} else if(isPalindromic(s, i - maxLength - 2, i)) {
res = s.substring(i - maxLength - 2, i + 1);
maxLength += 2;
}
}
if(maxLength == 0) res = s.substring(0, 1); // 注意只有单个字母是回文的情况
return res;
}
private boolean isPalindromic(String s, int begin, int end) {
if(begin < 0) return false;
while(begin < end) {
if(s.charAt(begin) != s.charAt(end)) return false;
begin++;
end--;
}
return true;
}
}