1 """ 2 Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 3 Example 1: 4 Input: "babad" 5 Output: "bab" 6 Note: "aba" is also a valid answer. 7 Example 2: 8 Input: "cbbd" 9 Output: "bb" 10 """ 11 12 """ 13 解法一:中心向两边扩张法 14 分了奇数和偶数两种情况 15 当s[l] == s[r] 16 l--, r++ 17 """ 18 class Solution: 19 def longestPalindrome(self, s): 20 res = '' 21 for i in range(len(s)): 22 # odd 'aba' 23 temp = self.palindromic(s, i, i) 24 if len(res) < len(temp): 25 res = temp 26 # even 'abba' 27 temp = self.palindromic(s, i, i+1) 28 if len(res) < len(temp): 29 res = temp 30 return res 31 # get the longest palindrome, l, r are the middle indexes 32 # from inner to outer 33 def palindromic(self, s, l, r): 34 while l >= 0 and r <= len(s) - 1 and s[l] == s[r]: 35 l -= 1 36 r += 1 37 return s[l+1: r] 38 """ 39 用动态规划做 40 """ 41 class Solution(object): 42 def longestPalindrome(self, s): 43 if s is None: 44 return '' 45 ret = '' 46 lens = len(s) 47 max = 0 48 dp = [[0] * lens for i in range(lens)] 49 #产生一个lens*lens全0二维数组,dp数组后面存储True或False 50 for j in range(lens): 51 for i in range(j + 1): 52 dp[i][j] = ((s[i] == s[j]) and (j - i <= 2 or dp[i + 1][j - 1])) 53 #如果s[i]=s[j]说明串的首尾相同, 54 # 并且j-i为0表示只有一个字符必为回文, 55 # j-i=1两个字符切相等必为回文, 56 # j-i=2三个字符首尾相同无论中间是什么必为回文, 57 # 或者dp[i + 1][j - 1]为真表示去掉首尾为回文,而新加的首尾相同必为回文。 58 if dp[i][j] and j - i + 1 > max: 59 max = j - i + 1 60 ret = s[i:j + 1] 61 #表示i开头j结束的串回文并且最长则更新长度max和回文串ret。 62 return ret