(力扣记录)5. 最长回文子串

数据结构/算法:动态规划

时间复杂度:O(n^2)

空间复杂度:O(1)

代码实现:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        leng = 0
        res = ''

        # odd:
        for i in range(len(s)):
            l, r = i, i
            while l >= 0 and r < len(s) and s[l] == s[r]:
                if r - l + 1 > leng:
                    leng = r - l + 1
                    res = s[l : r + 1]
                l -= 1
                r += 1

        # even:
        for i in range(len(s)):
            l, r = i, i + 1
            while l >= 0 and r < len(s) and s[l] == s[r]:
                if r - l + 1 > leng:
                    leng = r - l + 1
                    res = s[l : r + 1]
                l -= 1
                r += 1

        return res

你可能感兴趣的:(力扣算法题目记录,leetcode,数据结构,算法,python)