leetcode -. 5 palindromic longest substring

我的程序:
class
Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if s=='': return '' if len(s)==1: return s res=[] for i in range(len(s)): c=s[i:].count(s[i]) if c !=1: b=s[::-1].index(s[i]) j=len(s)-b-1 if s[i:j+1]==s[i:j+1][::-1] and i!=j: res.append(s[i:j+1]) else: c-=1 t=s[i:j] if len(t)==2: if t[0]==t[1]: res.append(t) break else: break b=t[::-1].index(t[0]) j=len(t)-b-1 if t[:j+1]==t[:j+1][::-1] and j!=0: res.append(t[:j+1]) c-=1 while c>1: t=s[i:i+j] if len(t)==2: if t[0]==t[1]: res.append(t) break else: break b=t[::-1].index(t[0]) j=len(t)-b-1 if t[:j+1]==t[:j+1][::-1] and j!=0: res.append(t[:j+1]) c-=1 if len(res)==0: return s[0] if len(res)==1: return res[0] m=max(len(res[i]) for i in range(len(res))) for i in range(len(res)): if len(res[i])==m: return res[i]
When execution: 2192 ms, beat the 50.51% of all users in Python submission
Memory consumption: 115.1 MB, beat the 5.06% of all users in Python submission
 
Although not easy to do it in about two hours, but there was still a place very long-winded.
When the execution of 20 is MS examples
 class Solution (Object):
     DEF longestPalindrome (Self, S):
         "" " 
        : type S: STR 
        : rtype: STR 
        " "" 
     IF len (S) < 2 or S == S [: : -1]:
        return S

        length = 1

        even_medium = 0
        even_left = 0
        for i in range(len(s) - 1):
            if i - even_left >= 0 and s[i - even_left] == s[i + 1]:
                substring = s[i - even_left: i + 2]
                if substring == substring[: : -1]:
                    even_medium = i
                    length = even_left + 2
                    even_left = even_left + 2

        odd_medium = 0            
        half = (length + 1) // 2
        odd_left = (length + 1) // 2
        for j in range(half, len(s) - half):
            if j - odd_left >= 0 and s[j - odd_left] == s[j + half]:
                substring = s[j - odd_left: j + half + 1]
                if substring == substring[: : -1]:
                    odd_medium = j
                    length = odd_left + half + 1
                    odd_left = odd_left + 2

        if length % 2 == 0:
            return s[even_medium + 2 - length: even_medium + 2]
        else:
            if length == 1:
                return s[0]
            else:
                return s[odd_medium + half + 1 - length: odd_medium + half + 1]

Analysis and improvement:

The inside of my program

        if s=='':
            return ''
        if len(s)==1:
            return s

Replaced by:

        if len(s) < 2 or s == s[::-1]:
            return s

 

No other closer look. . . .

                                                                        ——2019.10.11

 
 
 

Guess you like

Origin www.cnblogs.com/taoyuxin/p/11653794.html
Recommended