The longest substring palindromic Longest Palindromic Substring

(1) violence to solve

class Solution:
    def longestPalindrome(self, s: str) -> str:
        maxlen=0
        result=''
        for i in range(len(s)):
            for j in range(i,len(s)+1):##注意首尾坐标
                if s[i:j]==s[i:j][::-1]:
                    if j-i>maxlen:
                        maxlen=j-i
                        result=s[i:j]
                        #print(result)
        return result    

(2) dynamic programming, to improve (1)

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n=len(s)
        arr=[[0]*n for i in range(n)]
        maxlen=0
        result=''

        for j in range(n):
            for i in range(j+1):
                if (j-i<2 or arr[i+1][j-1]==1) and s[i]==s[j]:
                    arr[i][j]=1
                if arr[i][j] and j-i+1>maxlen:
                    maxlen=j-i+1
                    result=s[i:j+1]
        return result

3. Locate the center of the palindrome sequence, and can be extended to both sides.

We want parity center position considered separately, if the string length is odd, then the center is only one element; if the string is even, then the center of the two elements.

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n=len(s)
        def expandAroundCenter(left, right):
            L,R=left,right
            while L>=0 and R<len(s) and s[L]==s[R]:
                L+=-1
                R+=1
            return R-L-1

        maxlen=0
        result=''
        for i in range(n):
            len1=expandAroundCenter(i,i)#中间是奇数
            len2=expandAroundCenter(i,i+1)#中间是偶数
            mlen=max(len1,len2)
            if mlen>maxlen:
                maxlen=mlen
                result=s[i-(maxlen-1)//2:i+maxlen//2+1]
                
        return result

4. The first determination of the right border palindromic sequence i, then the right boundary iretrieve the text string to the left. Suppose ithe longest substring palindromic length before l, then we need to check each i+1left length of the string l+2and l+1sub-string string is not a palindrome. If l+2a palindromic sequence, then the maximum length of the string to become l+2, for l+1the same reason.

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n=len(s)
        if (len(s)<2) or s==s[::-1]:
            return s
        
        maxlen=1
        left=0
        for i in range(1,len(s)):
            s2=s[i-maxlen-1:i+1]   #check L+2
            s1=s[i-maxlen:i+1]  #check L+1
            if i-maxlen-1>=0 and s2==s2[::-1]:
                left=i-maxlen-1
                maxlen+=2
            elif i-maxlen>=0 and s1==s1[::-1]:
                left=i-maxlen
                maxlen+=1
            
        return s[left:left+maxlen]
    

Published 163 original articles · won praise 90 · views 6256

Guess you like

Origin blog.csdn.net/weixin_45405128/article/details/104433655
Recommended