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. 两个指针解法,注意中间位置是单个数还是双数
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. 动态规划解法
- 动态规划公式
s[i] == s[j] and dp[i+1][j-1]
, 如果两头相等,并且子集dp[i+1][j-1]
已经证实过,就扩大回文到[i, j]
- 必须从小到大,所以就要设置步长diff。并且优先处理单步的问题
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]