classSolution{ public String longestPalindrome(String s){ if (s == null) returnnull; int len = s.length(); if (len < 2) return s;
char[] chars = s.toCharArray(); int start = 0, max_len = 1; for (int i = 0; i < len - 1; i++) { int oddLen = expandAroundCenter(chars, i, i); //奇数 int evenLen = expandAroundCenter(chars, i, i + 1); //偶数
//begin和end都可以取到 intexpandAroundCenter(char[] chars, int begin, int end){ // 当 left = right 时,回文中心是一个字符,回文串的长度是奇数 // 当 left = right + 1 时,回文中心是两个字符,回文串的长度是偶数 int len = chars.length; int i = begin, j = end; while (i >= 0 && j < len) { if (chars[i] == chars[j]) { i--; j++; } else { break; } } //注意循环跳出之后,chars[i] != chars[j] //回文串的长度是 j - i + 1 - 2 = j - i - 1 return j - i - 1; } }