任务描述
思路
- 动态规划,使用一个二维bool矩阵来记录Sij是否是回文串,Sij表示字符串
- 当Sij是回文串时,同理Sij的子集S(i+1)(j-1)也是一个回文串,或者i,j之间间隔<=1
代码实现
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return s
longest = 1
ans = s[0]
size = len(s)
dp_matrix = [[False for _ in range(size)] for _ in range(size)]
for tail in range(1,size):
for head in range(tail):
if s[head]==s[tail] and (head>=tail-2 or dp_matrix[head+1][tail-1]):
dp_matrix[head][tail] = True
if tail-head+1>longest:
longest = tail-head+1
ans = s[head:tail+1]
return ans