class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if not s: return '' # 先将任一单个字母作为结果 start = 0 maxlen = 1 dp = [[0 for __ in range(len(s))] for __ in range(len(s))] # 将长度1和长度2(相同字母)情况初始化赋值 for i in range(len(s)): dp[i][i] = 1 if (i < len(s) - 1) and (s[i] == s[i+1]): dp[i][i+1] = 1 start = i maxlen = 2 # for line in dp: # print line # 注意:不可横向遍历,否则例如abcba,是无法先将bcb置为1的,进而无法将abcba置为1 # 从长度3开始 for length in range(3, len(s)+1): for i in range(len(s)-length+1): j = i + length - 1 if (dp[i+1][j-1] == 1) and s[i] == s[j]: dp[i][j] = 1 if length > maxlen: start = i maxlen = length # for line in dp: # print line return s[start:start+maxlen]
class Solution(object): def getlongestpalindrome(self, s, l, r): while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1 return s[l+1 : r] # 例如bab,最后l=-1,r=3,所以要s[l+1 : r]也就是[0,3] def longestPalindrome(self, s): """ :type s: str :rtype: str """ palindrome = '' for i in range(len(s)): len1 = len(self.getlongestpalindrome(s, i, i)) # len1是中间是单一字母的回文数 if len1 > len(palindrome): palindrome = self.getlongestpalindrome(s, i, i) len2 = len(self.getlongestpalindrome(s, i, i + 1)) # len2是中间是和后面一个字母相同的回文数 if len2 > len(palindrome): palindrome = self.getlongestpalindrome(s, i, i + 1) return palindrome