LeetCode Longest Palindromic Substring

LeetCode解题之Longest Palindromic Substring

原题

找到一个字符串的最长回文子字符串,该字符串长度不超过1000,且只有唯一一个最长回文子串。

注意点:

  • 返回结果是整个子字符串,不是它的长度
  • 回文字符串要考虑奇偶的情况

例子:

输入: s=”abae”
输出: aba

输入: s=”abbae”
输出: abba

解题思路

依次把每一个字符当做回文字符串的中间字符,找到以该字符为中间字符的回文串的最大长度。分别对奇偶的情况进行讨论,接下来的关键就是对边界的把握,确保下标不要越界。当子串已经包含首字符或最后一个字符且此时还是回文串的时候,下标分别会向两边多移一位,需要补回来。

AC源码

class Solution(object):
    def longestPalindrome(self, s):
        """ :type s: str :rtype: str """
        if not s:
            return
        n = len(s)
        if n == 1:
            return s
        # Left index of the target substring
        l = 0
        # Right index of the target substring
        r = 0
        # Length of the longest palindromic substring for now
        m = 0
        # Length of the current substring
        c = 0
        # Whether the substring contains the first character or last character and is palindromic
        b = True
        for i in range(0, n):
            # Odd situation
            for j in range(0, min(n - i, i + 1)):
                if (s[i - j] != s[i + j]):
                    b = False
                    break
                else:
                    c = 2 * j + 1
            if (c > m):
                l = i - j + 1 - b
                r = i + j + b
                m = c
            b = True
            # Even situation
            for j in range(0, min(n - i - 1, i + 1)):
                if (s[i - j] != s[i + j + 1]):
                    b = False
                    break
                else:
                    c = 2 * j + 2
            if (c > m):
                l = i - j + 1 - b
                r = i + j + 1 + b
                m = c
            b = True
        return s[l:r]

# Test cases
if __name__ == "__main__":
    assert Solution().longestPalindrome("aba") == "aba"
    assert Solution().longestPalindrome("abba") == "abba"
    assert Solution().longestPalindrome("xaba") == "aba"
    assert Solution().longestPalindrome("xabba") == "abba"

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

你可能感兴趣的:(LeetCode,算法,python,回文,palindrom)