LeetCode5. 最长回文子串647. 回文子串(双指针、中心扩展算法)

5. 最长回文子串

https://leetcode-cn.com/problems/longest-palindromic-substring/

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

代码详解

class Solution(object):
    def longestPalindrome(self, s):
        res = ""
        for i in range(len(s)):
            # 法一
            # # odd case, like "aba"
            # tmp = self.helper(s, i, i)
            # if len(tmp) > len(res):
            #     res = tmp
            # # even case, like "abba"
            # tmp = self.helper(s, i, i + 1)
            # if len(tmp) > len(res):
            #     res = tmp

            # 法二:简单写法
            res = max(self.helper(s, i, i), self.helper(s, i, i + 1), res, key=len)
        return res

    # get the longest palindrome, l, r are the middle indexes
    # from inner to outer
    def helper(self, s, l, r):
        # while循环由于l或r超出范围而停止,或者因为s[l] != s[r]
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        # print(l, r)
        return s[l + 1:r]  # 最长的回文既不属于s[l]也s[r]不能成为其一部分,辅助函数返回s[l+1:r](左侧包括且右侧排除)

S = Solution()
s = 'babad'
print(S.longestPalindrome(s))

题解

https://leetcode.com/problems/longest-palindromic-substring/discuss/2954/Python-easy-to-understand-solution-with-comments-(from-middle-to-two-ends).

思路

https://labuladong.gitbook.io/algo/gao-pin-mian-shi-xi-lie/zui-chang-hui-wen-zi-chuan

647. 回文子串

https://leetcode-cn.com/problems/palindromic-substrings/

给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。

具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。

代码详解

中心扩展算法

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        ans = 0
        n = len(s)
        for center in range(2*n-1):
            left = center // 2
            right = left + center % 2
            while left >= 0 and right <= n - 1 and s[left] == s[right]:
                ans += 1
                left -= 1
                right += 1
        return ans
    
S = Solution()
ss = 'aaa'
print(S.countSubstrings(ss))

https://leetcode-cn.com/problems/palindromic-substrings/solution/liang-dao-hui-wen-zi-chuan-de-jie-fa-xiang-jie-zho/

你可能感兴趣的:(String,LeetCode)