• En
  • Signup
  • 刷题上岸
  • Today 0
  • Post 12
  • Followed 1
  • 捐助

    请在小工具里添加二维码

    刷题上岸 刷题上岸 关注:1 内容:12

    5. Longest Palindromic Substring

  • 查看作者
  • 打赏作者
  • 拉黑名单
    • 刷题上岸
    • 等级6
      土豪

      Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

      Example 1:

      Input: "babad"Output: "bab"Note: "aba" is also a valid answer.

      Example 2:

      Input: "cbbd"Output: "bb"

      class Solution:
       
          def longestPalindrome(self, s: str) -> str:
              if not s or len(s)<=1:
                  return s
              length = len(s)
              start = 0
              res = 1
              mid = 0
              while mid+res//2 < length:
                  left = mid
                  right = mid
                  while right<length-1 and s[right]==s[right+1]:
                      right += 1
                  mid = right+1
                  while right<length-1 and left>0 and s[right+1]==s[left-1]:
                      right += 1
                      left -= 1
                  if right-left+1 > res:
                      start = left
                      res = right-left+1
              return s[start: start+res]

      请登录之后再进行评论

      登录
    • Tasks
    • Current Activities
    • Back to Top