【力扣】4. 最长回文子串--Python实现

【题目描述】
给你一个字符串 s,找到 s 中最长的回文子串。

示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。

示例 2:
输入:s = “cbbd”
输出:“bb”

示例 3:
输入:s = “a”
输出:“a”

示例 4:
输入:s = “ac”
输出:“a”

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

【解题思路】
用动态规划来解这道题,dp[i][j]代表从第i个位置到第j个位置之间能不能构成回文子串,则有dp[i+1][j-1] 且 s[i]==s[j]时dp[i][j]才能构成回文子串,用l来记录i和j之间的距离,则:如果l=0,代表i和j指向同一处,必能构成一个回文子串;如果l=1,代表i和j相邻,只有当s[i]==s[j]时才能构成。用Python实现的代码如下:

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        dp = [[False]*len(s) for _ in range(len(s))]
        ans = ""

        for l in range(len(s)):
            for i in range(len(s)):
                j = i+l
                if j>=len(s): break
                if l==0: dp[i][j]=True
                elif l==1: dp[i][j]=(s[i]==s[j])
                else:
                    dp[i][j]=(dp[i+1][j-1] and s[i]==s[j])
                if dp[i][j] and l+1>len(ans):
                    ans = s[i:j+1]
        return ans

你可能感兴趣的:(力扣,动态规划,leetcode,python,算法,字符串)