给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
示例 2:
输入:s = “cbbd”
输出:“bb”
- 代码是根据B站上的一位up主写的
- 使用动态规划算法
- 从小字符串衍生相关字符串的状态
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s:
return s
l = len(s)
state = [[False for _ in range(l)] for _ in range(l)]
max_length,index = 1,0
for i in range(l):
state[i][i] = True
for j in range(1,l):
for i in range(j):
if s[i] == s[j]:
if j - i < 3:
state[i][j] = True
else:
state[i][j] = state[i+1][j-1]
temp_length = j - i + 1
if state[i][j]:
if temp_length > max_length:
max_length,index = temp_length,i
return s[index:index+max_length]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring
来源:Bilibili
链接:https://www.bilibili.com/video/av668623130?from=search&seid=11772670618775325440&spm_id_from=333.337.0.0