题 目:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
思 路:
输入一个字符串:s[n],若len(s)为1或者2(两个字符一样),即输出。若len>=3,从第二个字符开始,设为中间值,由中间值向字符两侧扩展对比,直到匹配不上或者字符串结束。
class Solution(object): def longestPalindrome(self,s): size=len(s) if size==1: return s if size==2: if s[0]==s[1]: return s return s[0] maxp=1 ans=s[0] i=0 while i<size: j=i+1 while j<size: if s[i]==s[j]: j+=1 else: break print j k=0 while i-k-1>=0 and j+k<=size-1: if s[i-k-1]!=s[j+k]: break k+=1 print i-k-1 if j-i+2*k>maxp: maxp=j-i+2*k ans=s[i-k:j+k] if j+k==size-1: break i=j return ans
实验结果: