题目

给定一个字符串s,找到s中最长的回文子串。你可以假设s的最大长度为1000。
image.png

思路

中心扩散
以str[i]为中心
或者如果str[i] == str[i + 1],以str[i]和str[i + 1]这个整体为中心

  1. class Solution:
  2. def longestPalindrome(self, s: str) -> str:
  3. length = len(s)
  4. if length <= 1: return s
  5. max_palindrome = ''
  6. for i in range(length):
  7. tmp = self.helper(s, i, length)
  8. max_palindrome = tmp if len(tmp) > len(max_palindrome) else max_palindrome
  9. return max_palindrome
  10. def helper(self, s, mid, length):
  11. # 以当前mid为中心遍历一遍
  12. left, right = mid - 1, mid + 1
  13. odd_str = s[mid]
  14. while left >= 0 and right < length and s[left] == s[right]:
  15. odd_str = s[left : right + 1]
  16. left -= 1
  17. right += 1
  18. even_str = s[mid]
  19. if mid + 1 < length and s[mid] == s[mid + 1]:
  20. left = mid
  21. right = mid + 1
  22. even_str = s[left : right + 1]
  23. while left >= 0 and right < length and s[left] == s[right]:
  24. even_str = s[left : right + 1]
  25. left -= 1
  26. right += 1
  27. return odd_str if len(odd_str) > len(even_str) else even_str

https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zui-chang-hui-wen-zi-chuan-by-leetcode-solution/

  • 需要进一步完善