Longest Palindromic Substring - LeetCode (leetcode-cn.com)
Given a string s, find the longest palindrome substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also the answer that meets the meaning of the question.
Example 2:Input: s = "cbbd"
Output: "bb"
hint:
1 <= s.length <= 1000
s only consists of numbers and English lettersSource: LeetCode
dynamic programming
Idea: Define dp[i][j] as whether the string starting from the i-th character of the string to the end of the j-th character is a palindrome
(i<=j)
Substring s[l,r], if s[l+1:r-1] is a palindrome, then just check whether s[l] and s[r] are equal
即dp[l][r]=dp[l+1][r-1] and s[l]==s[r]
In a special case, if l+1 is equal to r-1, it means that there is only one element between the two endpoints,
dp[l][r]=True if s[l]==s[r] else False, in fact, the above case can also be incorporated, because an element is a palindrome by itself
If l+1>r-1, it means that there is no element between the two endpoints, then it is only necessary to directly judge whether s[i] and s[r] are equal.
In the above explanation process, we all emphasized the two endpoints, but because i<=j, when i=j, the two points overlap, and the assignment can be done directly.
Summary: Define the meaning of the equation, find out the state transition equation, and determine the boundary conditions based on the state transition equation.
class Solution:
def longestPalindrome(self, s: str) -> str:
n=len(s)
dp=[[False]*n for i in range(n)]
dp[n-1][n-1]=True
a,b,ans=0,0,0
for l in range(n-2,-1,-1):
for r in range(l,n):
if l==r:
dp[l][r]=True
elif l+1>r-1:
dp[l][r]=True if s[l]==s[r] else False
else:
dp[l][r]=dp[l+1][r-1] and s[r]==s[l]
if dp[l][r] and r-l>=ans:
a,b,ans=l,r,abs(l-r)
return s[a:b+1]