题目
思路
dp,构造上三角矩阵。
代码
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if not s: return null
length = len(s)
#init
dp = [[0 for i in range(length)] for j in range(length)]
#update dp
for i in range(length)[::-1]:
for j in range(i, length):
if i == j:
dp[i][j] = 1
continue
if s[i] == s[j]:
if j == i + 1:
dp[i][j] = 2
elif dp[i + 1][j - 1]:
dp[i][j] = dp[i + 1][j - 1] + 2
maxi = 0; maxj = 0; maxNum = 0
for i in range(length):
for j in range(i, length):
if dp[i][j] > maxNum:
maxi = i; maxj = j; maxNum = dp[i][j]
return s[maxi:maxj + 1]