5. Longest Palindromic Substring
Medium
10497679Add to ListShare
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd" Output: "bb"
Example 3:
Input: s = "a" Output: "a"
Example 4:
Input: s = "ac" Output: "a"
Constraints:
1 <= s.length <= 1000sconsist of only digits and English letters (lower-case and/or upper-case)
class Solution:
max_len = start = end = 0
def longestPalindrome(self, s: str) -> str:
"""
解题思路1:暴力枚举中心点,向两边展开
时间复杂度:O(n^2),空间复杂度:O(1)
"""
if s is None or len(s) <= 0:
return ""
def expand(cur_len: int, l: int, r: int):
while l >= 0 and r < len(s) and s[l] == s[r]:
cur_len += 2
if cur_len > self.max_len:
self.max_len = cur_len
self.start = l
self.end = r
l -= 1
r += 1
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
# 中心对称
expand(0, i, i + 1)
expand(1, i - 1, i + 1)
self.end += 1
return s[self.start:self.end]
还有个解法:Manacher's Algorithm 马拉车算法:时间复杂度O(n)
本文介绍了一种寻找字符串中最长回文子串的有效算法。通过两种方法——暴力枚举中心点并逐步向外扩展和使用马拉车算法(Manacher's Algorithm),文章详细解释了其背后的原理及实现过程。

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



