class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ lenStr = len(s) if lenStr <= 0: return 0 maxLen = 0 tmpLen = 0 tmpRes = ‘‘ for i in range(0,lenStr): #odd numbers j=0 tmpLen=0 while i-j >= 0 and i+j < lenStr and s[i-j] == s[i+j]: tmpLen = 2*j +1 j+=1 if tmpLen > maxLen: maxLen = tmpLen #i-j+1 plus one because first: j+=1 then judge s[i-j] == s[i+i] #so when the while cycle stop, the j is bigger one than the j that make while condition establish tmpRes = s[i-j+1:i+j] #even numbers j=0 tmpLen=0 while i-j>=0 and i+j+1 < lenStr and s[i-j] == s[i+j+1]: tmpLen = 2*j + 2 j+=1 if tmpLen > maxLen: maxLen = tmpLen tmpRes = s[i-j+1:i+j+1] return tmpRes
时间: 2024-10-27 04:37:52