Python版-LeetCode 学习:5. 最长回文子串

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring

方法1:动态规划法

class Solution:
    def longestPalindrome(self, s: str) -> str:
        length=len(s)
        if length<=1: return s
        dp=[[ False for _ in s ]for _ in s]

        start=0
        max_len=1
        for j in range(1,length):
            for i in range(0,j):
                if j-i<3:
                    dp[i][j]= s[i]==s[j]
                else:
                    dp[i][j]= s[i]==s[j] and dp[i+1][j-1]

                if dp[i][j]:
                    cur_len=j-i+1
                    if cur_len>max_len:
                        max_len=cur_len
                        start=i
        
        return s[start:start+max_len]

方法2:

class Solution:
    def longestPalindrome(self, s: str) -> str:

        maxlen = 0
        start = 0
        if not s or s == "":
            return ""
        if s == s[::-1] or len(s) == 1:
            return s
        for i in range(1,len(s)):
            odd = s[i - maxlen - 1:i + 1]
            even = s[i - maxlen:i + 1]
            if odd == odd[::-1] and i - maxlen - 1  >= 0:
                start = i - maxlen - 1
                maxlen += 2
            elif even == even[::-1] and i- maxlen - 1 >= 0:
                start = i - maxlen
                maxlen += 1
        return s[start:start+maxlen]

 ps:

你可能感兴趣的:(LeetCode算法,leetcode,python,动态规划,算法)