leetcode 5-> Longest Palindromic Substring

class Solution(object):
    def get_f_l(self,s_length,s,list_all,last_d):
        max_l=0
        first_d=0
        last_d=0
        for i in range(len(list_all)):
            if((i+1)==len(list_all)):
                break
            for j in range(i+1,len(list_all)):
                diff=list_all[j]-list_all[i]+1
                if(list_all[i]==0):
                    if(list_all[j]==s_length-1):
                        if(s==s[::-1]):
                            return 0,list_all[j]
                    else:
                        if(s[:list_all[j]+1]==s[list_all[j]::-1]):
                            if(diff>max_l):
                                max_l=diff
                                first_d=0
                                last_d=list_all[j]
                else:
                    if(list_all[j]==s_length-1):
                        if(s[list_all[i]:]==s[list_all[j]:list_all[i]-1:-1]):
                            if(diff>max_l):
                                max_l=diff
                                first_d=list_all[i]
                                last_d=list_all[j]
                    else:
                        if(s[list_all[i]:list_all[j]+1]==s[list_all[j]:list_all[i]-1:-1]):
                            if(diff>max_l):
                                max_l=diff
                                first_d=list_all[i]
                                last_d=list_all[j]
        return first_d,last_d
    
    def longestPalindrome(self, s):
        s_length=len(s)
        max_len=0
        f=0
        l=0
        s_x=set(s)
        for i in s_x:
            last_d=s.rfind(i)
            list_all=[]
            oper_s=s
            i_num=0
            while(True):
                x=s.find(i,i_num)
                if(not x==-1):
                    i_num=x+1
                    list_all.append(x)
                else:
                    break
            if(len(list_all)==1):
                continue

            first_d,last_d=self.get_f_l(s_length,s,list_all,last_d)
            diff=last_d-first_d
            if(diff>max_len):
                f=first_d
                l=last_d
                max_len=diff
        return s[f:l+1]
原文地址:https://www.cnblogs.com/sea-stream/p/10493416.html