[TwoPointer]5. Longest Palindromic Substring

  • 分类:String/TwoPointer
  • 时间复杂度: O(n^2)
  • 空间复杂度: O(1)

5. Longest Palindromic Substring

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 s==None:
            return ""
        
        myPalindrome=""
        
        for i in range(len(s)):
            sub=self.findPalindrome(i,i,s)
            if len(sub)>len(myPalindrome):
                myPalindrome=sub
            sub=self.findPalindrome(i,i+1,s)
            if len(sub)>len(myPalindrome):
                myPalindrome=sub
        
        return myPalindrome
    
    def findPalindrome(self,left,right,s):
        while left>=0 and right

讨论:

  1. 并不是一看就知道要用双指针的方法,但是以后一看到Palindromic,估计第一时间就能想到用双指针吧,这还是反向双指针orz
  2. 这道题先找每一个中点,然后再往两边展开
  3. 到bug free用了3步:
  • 一开始没有range(len(s))这是个初级错误哦
  • s[left+1:right],这里也是写成了left-1,想当然了
  • 还有一个拼错的低级错误
    4.so 以后做完题觉得o98k的话一定要返回头来检查

你可能感兴趣的:([TwoPointer]5. Longest Palindromic Substring)