数据结构/算法:动态规划
时间复杂度:O(n^2)
空间复杂度:O(1)
代码实现:
class Solution:
def longestPalindrome(self, s: str) -> str:
leng = 0
res = ''
# odd:
for i in range(len(s)):
l, r = i, i
while l >= 0 and r < len(s) and s[l] == s[r]:
if r - l + 1 > leng:
leng = r - l + 1
res = s[l : r + 1]
l -= 1
r += 1
# even:
for i in range(len(s)):
l, r = i, i + 1
while l >= 0 and r < len(s) and s[l] == s[r]:
if r - l + 1 > leng:
leng = r - l + 1
res = s[l : r + 1]
l -= 1
r += 1
return res
本文介绍了使用动态规划方法求解字符串中最长回文子串的问题,代码实现中考虑了奇数和偶数长度的子串,时间复杂度为O(n^2),空间复杂度保持在O(1)。
2387

被折叠的 条评论
为什么被折叠?



