📜  门| GATE CS 1996 |问题5(1)

📅  最后修改于: 2023-12-03 15:42:10.538000             🧑  作者: Mango

GATE CS 1996 | Problem 5

本题要求实现一个函数,给定一个字符串,找到其中最长的回文子串。回文子串即正反读起来都一样的字符串。

示例
Input: "babad"
Output: "bab" 或 "aba"

Input: "cbbd"
Output: "bb"
思路

遍历字符串,以每个字符为中心向两边扩展,找到最长的回文子串。需要注意奇偶回文串的区别。

代码示例:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        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
        return res
     
    # get the longest palindrome, l, r are the middle indexes   
    # from inner to outer
    def helper(self, s: str, l: int, r: int) -> str:
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        return s[l + 1: r]
时间复杂度

时间复杂度为$O(n^2)$,其中n为字符串的长度。遍历n个字符,每个字符向两边扩展的时间复杂度为$O(n)$。因此总时间复杂度为$O(n^2)$。

空间复杂度

空间复杂度为$O(1)$。只使用了常数级别的额外空间。

完整代码
class Solution:
    def longestPalindrome(self, s: str) -> str:
        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
        return res
     
    # get the longest palindrome, l, r are the middle indexes   
    # from inner to outer
    def helper(self, s: str, l: int, r: int) -> str:
        while l >= 0 and r < len(s) and s[l] == s[r]:
            l -= 1
            r += 1
        return s[l + 1: r]