找出给出的字符串S中最长的回文子串。假设S的最大长度为1000,并且只存在唯一解。
class Solution: def longestPalindrome(self , s ): # write code here l,r=0,0 maxstr='' flag=0 while(r!=len(s)): temstr='' temstr=s[l:r] if s[l:r]!=temstr[::-1] and flag==0: r+=1 elif s[l:r]==temstr[::-1] and len(s[l:r])>=2 and flag==0: if len(maxstr)<len(s[l:r]): maxstr=s[l:r] flag=1 r+=1 elif s[l:r]==temstr[::-1] and flag==1: if len(maxstr)<len(s[l:r]): maxstr=s[l:r] r+=1 elif s[l:r]!=temstr[::-1] and flag==1: l+=1 if len(maxstr)<len(s[l:r]): maxstr=s[l:r] else: r+=1 temstr=s[l:r] if s[l:r]==temstr[::-1]: if len(maxstr) < len(s[l:r]): maxstr = s[l:r] elif s[l:r]!=temstr[::-1]: while(l<r and s[l:r]!=temstr[::-1]): l+=1 temstr=s[l:r] if s[l:r]==temstr[::-1]: if len(maxstr) < len(s[l:r]): maxstr = s[l:r] return maxstr
#python实现 class Solution: def longestPalindrome(self , s )-> str: # write code here res = '' for i in range(len(s)): start = max(0,i-len(res)-1) temp = s[start:i+1] if temp == temp[::-1]: res = temp else: temp = temp[1:] if temp == temp[::-1]: res = temp return res