[LeetCode] 5. Longest Palindromic Substring题解

Problem Description

Given a string s , where to find the longest substring palindromic, assuming s is the maximum length of 1000.

Example 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是正确的答案
复制代码

Example 2:

Input: "cbbd"
Output: "bb"
复制代码

Difficulty

Medium

Problem-solving ideas

Noted the symmetry of the palindrome, we only need to traverse the s process, assuming that each character is a palindrome center, a palindrome for each center, we continue to expand to both sides, while its symmetry detection, to find the boundaries of the palindrome, and record length, finally, when traversed s later, we examined the s all palindrome, of course, can be obtained s longest substring palindromic. Time complexity of this method O (n ^ 2).

It should be noted that the palindrome two forms: single-center and two-center, so when we walk through each character, not only to the current character as a single center palindrome center, but also the current and the next character as a character Center palindromic double center, and respectively two extended to both sides of the center.

All code is as follows:

class Solution():
    def expand(self, left, right, s):
        """
        expand from middle point
        """
        if right >= len(s) or s[left] != s[right]:
            return 0

        while left-1 >= 0 and right+1 < len(s) and s[left-1] == s[right+1]:
            left -= 1
            right += 1

        return right + 1 - left

    def longest_palindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s:
            return ""

        middle = 0
        max_len = 0
        for i in range(len(s)):
            len1 = self.expand(i, i, s)
            len2 = self.expand(i, i+1, s)
            longer = max(len1, len2)
            if longer > max_len:
                max_len = longer
                middle = i

        begin = middle-int((max_len-1)/2)
        return s[begin:begin+max_len]
复制代码

Reproduced in: https: //juejin.im/post/5cf7d335e51d4556f76e8058

Guess you like

Origin blog.csdn.net/weixin_34162401/article/details/91455409