Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
找到一个字符串中的最长连续回文串.
以一个字符或两个字符为中心,向两边扩展找回文串.
public class A05LongestPalindromicSubstring_1 {
public String longestPalindrome(String s) {
int begin = 0, end = 1;
int len1, len2, len;
for(int i = 0; i < s.length(); i++) {
len1 = findPalindrome(s, i, i);
len2 = findPalindrome(s, i, i + 1);
len = Math.max(len1, len2);
if(len > end - begin) {
begin = i - (len - 1) / 2;
end = i + 1 + len / 2;
}
}
return s.substring(begin, end);
}
public int findPalindrome(String s, int left, int right) {
while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
}