classSolution { public String longestPalindrome(String s) { intmax=0, start = 0, end = 0; for (inti=0; i < s.length() - 1; i++) { // 以当前字符为中心向两边扩展 intlen1= expand(s, i, i); // 以当前字符与相邻字符为中心向两边扩展 intlen2= expand(s, i, i + 1); intlen= Math.max(len1, len2); if (max < len) { max = len; // 重新计算子字符串位置 start = i - (len - 1) / 2; end = i + len / 2; } } return s.substring(start, end + 1); }
privateintexpand(String s, int left, int right) { while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { left--; right++; } return right - left - 1; }