1. # 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
    2. #
    3. # 示例 1:
    4. #
    5. # 输入: "babad"
    6. # 输出: "bab"
    7. # 注意: "aba" 也是一个有效答案。
    8. #
    9. #
    10. # 示例 2:
    11. #
    12. # 输入: "cbbd"
    13. # 输出: "bb"
    14. #
    15. # Related Topics 字符串 动态规划
    16. # 👍 2558 👎 0
    17. # leetcode submit region begin(Prohibit modification and deletion)
    18. class Solution(object):
    19. def longestPalindrome(self, s):
    20. """
    21. :type s: str
    22. :rtype: str
    23. """
    24. max_l = 0
    25. res = ""
    26. for i in range(0, len(s)):
    27. # s[i] 为中心
    28. left, right = i, i
    29. while left >= 0 and right < len(s) and s[left] == s[right]:
    30. if max_l < right - left + 1:
    31. max_l = right - left + 1
    32. res = s[left:right + 1]
    33. left -= 1
    34. right += 1
    35. # s[i] s[i+1] 为中心
    36. left, right = i, i + 1
    37. while left >= 0 and right < len(s) and s[left] == s[right]:
    38. if max_l < right - left + 1:
    39. max_l = right - left + 1
    40. res = s[left:right + 1]
    41. left -= 1
    42. right += 1
    43. return res
    44. # leetcode submit region end(Prohibit modification and deletion)
    45. s = Solution()
    46. print(s.longestPalindrome("babad"))
    47. print(s.longestPalindrome("cbbd"))
    1. class Solution(object):
    2. def longestPalindrome(self, s):
    3. """
    4. :type s: str
    5. :rtype: str
    6. """
    7. start, end = 0, 0
    8. for index, item in enumerate(s):
    9. left1, right1 = self.expandAroundCenter(s, index, index)
    10. left2, right2 = self.expandAroundCenter(s, index, index + 1)
    11. if right1 - left1 > end - start:
    12. start, end = left1, right1
    13. if right2 - left2 > end - start:
    14. start, end = left2, right2
    15. return s[start: end + 1]
    16. def expandAroundCenter(self, s, left, right):
    17. while left > 0 and right < len(s) and s[left] == s[right]:
    18. left -= 1
    19. right += 1
    20. return left + 1, right - 1