5.Longest Palindromic Substring Leetcode Python

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.


这题有两种解法,第一种是一一把所有序列挑出来 比较他们是否是palidronme 然后挑出最长的。

这种解法是O(n^3)

会let

class Solution:
    # @return a string
    
    def checkpali(self,substr):
        for index in range(len(substr)):
            if substr[index]!=substr[len(substr)-index-1]:
                return False
        return True
    def longestPalindrome(self, s):
        substr=''
        for i in range(len(s)):
            for j in range(i,len(s)+1):
                if self.checkpali(s[i:j]):
                    if len(substr)<len(s[i:j]):
                        substr=s[i:j]
        return substr
第二种做法是每走一步,左右找出最长的palidronme 最后返回最长的palidronme这种做法的 复杂度是 O (n^2)

class Solution:
    # @return a string
    
    def pali(self,s,left,right):
        while left>=0 and right<len(s) and s[left]==s[right]:
            left-=1
            right+=1
        return s[left+1:right]
    
    def longestPalindrome(self, s):
        palistr=''
        for index in range(len(s)):
            if len(palistr)<len(self.pali(s,index,index)):
                palistr=self.pali(s,index,index)
            if len(palistr)<len(self.pali(s,index,index+1)):
                palistr=self.pali(s,index,index+1)
        return palistr
            
            


你可能感兴趣的:(LeetCode,array,python,L)