5. Longest Palindromic Substring (经典题)

本文介绍了一种寻找字符串中最长回文子串的有效算法。通过两种方法——暴力枚举中心点并逐步向外扩展和使用马拉车算法(Manacher's Algorithm),文章详细解释了其背后的原理及实现过程。

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 <= 1000
  • s consist 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)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值