5. Longest Palindromic Substring
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.
Example:
Input: "cbbd" Output: "bb"
1 class Solution: 2 def solve(self,s,l,r): 3 while r<len(s) and l>=0 and s[l]==s[r]: 4 l-=1 5 r+=1 6 return s[l+1:r] 7 def longestPalindrome(self,s): 8 if len(s) == 0: 9 return 0 10 max_string='' 11 for i in range(len(s)): 12 #奇数长度回文串如ababa 13 tmp=self.solve(s,i,i) 14 if len(tmp)>len(max_string): 15 max_string=tmp 16 #偶数回文串如abba 17 18 tmp=self.solve(s,i,i+1) 19 if len(tmp)>len(max_string): 20 max_string=tmp 21 22 return max_string
1 def solve(s,l,r): 2 while r<len(s) and l>=0 and s[l]==s[r]: 3 l-=1 4 r+=1 5 return s[l+1:r] 6 def longestPalindrome(s): 7 if len(s) == 0: 8 return 0 9 max_string='' 10 for i in range(len(s)): 11 #奇数长度回文串如ababa 12 tmp=solve(s,i,i) 13 if len(tmp)>len(max_string): 14 max_string=tmp 15 #偶数回文串如abba 16 17 tmp=solve(s,i,i+1) 18 if len(tmp)>len(max_string): 19 max_string=tmp 20 21 return max_string 22 23 24 25 26 print(longestPalindrome('ababa'))