public String longestPalindrome(String s){ sMaxLength = 0; leftIndex = 0; rightIndex = 0; if (s == null || s.length() <= 1) { return s; } for (int i = 0; i < s.length(); i++) { findLongestPalindromic(s, i, i);//odd findLongestPalindromic(s, i, i + 1);//even } return s.substring(leftIndex, rightIndex); }
publicvoidfindLongestPalindromic(String s, int low, int high){ while (low >= 0 && high <= s.length() - 1) { if (s.charAt(low) == s.charAt(high)) { int len = high - low + 1; if (len > sMaxLength) { sMaxLength = len; leftIndex = low; rightIndex = high + 1; } low--;//Bear in mind that changing index high++; } else { break; } } }