题目

最长回文子串 - 图1

解题思路

最长回文子串 - 图2

代码

  1. class Solution {
  2. public String longestPalindrome(String s) {
  3. if (s == null || s.length() < 1) {
  4. return "";
  5. }
  6. int start = 0, end = 0;
  7. for (int i = 0; i < s.length(); i++) {
  8. int len1 = expandAroundCenter(s, i, i);
  9. int len2 = expandAroundCenter(s, i, i + 1);
  10. int len = Math.max(len1, len2);
  11. if (len > end - start) {
  12. start = i - (len - 1) / 2;
  13. end = i + len / 2;
  14. }
  15. }
  16. return s.substring(start, end + 1);
  17. }
  18. public int expandAroundCenter(String s, int left, int right) {
  19. while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
  20. --left;
  21. ++right;
  22. }
  23. return right - left - 1;
  24. }
  25. }