5. Longest Palindromic Substring
Given a string s, return the longest
palindromic
substring
in s.
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Constraints:
- 1 <= s.length <= 1000
- s consist of only digits and English letters.
1. Two pointer solutions, pay attention to whether the middle position is a single number or a double number
class Solution:
def longestPalindrome(self, s: str) -> str:
def expand(i, j):
left = i
right = j
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return right - left - 1
ans = [0, 0]
for i in range(len(s)):
odd_len = expand(i ,i)
if odd_len > ans[1] - ans[0] + 1:
dist = odd_len // 2
ans = [i - dist, i + dist]
even_len = expand(i, i+1)
if even_len > ans[1] - ans[0] + 1:
dist = (even_len // 2) - 1
ans = [i - dist, i + 1 + dist]
i, j = ans
return s[i: j+1]
2. Dynamic programming solution
- Dynamic programming formula
s[i] == s[j] and dp[i+1][j-1]
, if both ends are equal, and the subsetdp[i+1][j-1]
has been verified, expand the palindrome to[i, j]
- It must be from small to large, so it is necessary to set the step size diff. And prioritize single-step issues
s[i] == s[i+1]
class Solution:
def longestPalindrome(self, s: str) -> str:
n = len(s)
dp = [[False] * n for _ in range(n)]
ans = [0, 0]
for i in range(n):
dp[i][i] = True
for i in range(n - 1):
if s[i] == s[i+1]:
dp[i][i+1] = True
ans = [i, i+1]
for diff in range(2, n):
for i in range(n - diff):
j = i + diff
if s[i] == s[j] and dp[i+1][j-1]:
dp[i][j] = True
ans = [i, j]
i, j = ans
return s[i: j+1]