题目
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
动态规划
定义dp[j][i]:表示字符串 s[j:i+1] 是回文子串长度。
初始化:当 j==i 时,代表只有一个字符,回文串的长度为1.
状态转移方程:
如果j = i + 1 , dp[j][i] = s[i] == s[j]
如果j > i + 1 , dp[j][i] = s[i] == s[j] && dp[i + 1][j - 1]
python代码
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
if n==1:
return s
dp = [[0]*n for i in range(n)]
start,end,maxL = 0,0,0
for i in range(n):
for j in range(i):
dp[j][i] = (s[j] == s[i]) and ((i-j<2)|dp[j+1][i-1])
if dp[j][i] and maxL<i-j+1:
start = j
end = i
maxL= i-j+1
dp[i][i] = 1
return s[start:end+1]