天天看點

Leetcode實戰:5.最長回文子串

題目:

給定一個字元串 s,找到 s 中最長的回文子串。你可以假設 s 的最大長度為 1000。

示例1:

輸入: "babad"
輸出: "bab"
注意: "aba" 也是一個有效答案
           

示例2:

輸入: "cbbd"
輸出: "bb"
           

算法實作:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        firststr = ''
        secondstr = ''
        for each in range(len(s) if len(s) < 1000 else 1000):
            m, n = each, each
            while m >= 0 and n <= len(s) - 1 and s[m] == s[n]:
                    if len(firststr) <= n - m + 1: firststr = s[m:n + 1]
                    m -= 1
                    n += 1
            m, n = each, each + 1
            while m >= 0 and n <= len(s) - 1 and s[m] == s[n]:
                    if len(secondstr) <= n - m + 1: secondstr = s[m:n + 1]
                    m -= 1
                    n += 1
        return firststr if len(firststr) > len(secondstr) else secondstr
           

結果:

Leetcode實戰:5.最長回文子串