最长回文子串——动态规划

"""
给你一个字符串 s,找到 s 中最长的回文子串。

如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。



示例 1:

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

输入:s = "cbbd"
输出:"bb"
"""

def longest_par(s):
    if not s:
        return ""

    n = len(s)
    dp = [[False]*n for _ in range(n)]
    ans = s[0]

    for i in range(n-1, -1, -1):
        dp[i][i] = True
        if i > 0 and s[i] == s[i-1]:
            dp[i-1][i] = True
            if len(ans) < 2:
                ans = s[i-1:i+1]

        for j in range(i+2, n):
            if s[i] == s[j]:
                dp[i][j] = dp[i+1][j-1]
                if dp[i][j] and len(ans) < j-i+1:
                    ans = s[i:j+1]
    return ans

print(longest_par("aabba"))
print(longest_par("aabbaa"))
print(longest_par("jbba"))
print(longest_par("jbbaa"))
print(longest_par("jbbjaa"))
print(longest_par(""))


# 下面是GPT4给的写法,感觉逻辑上比我的更清晰 def longestPalindromeDP(s): n = len(s) if n == 0: return "" start = 0 max_len = 1 dp = [[False] * n for _ in range(n)] # 单个字符是回文 for i in range(n): dp[i][i] = True # 两个字符相同是回文 for i in range(n - 1): if s[i] == s[i + 1]: dp[i][i + 1] = True start = i max_len = 2 # 遍历长度大于2的子串 for length in range(3, n + 1): for i in range(n - length + 1): j = i + length - 1 if s[i] == s[j] and dp[i + 1][j - 1]: dp[i][j] = True start = i max_len = length return s[start:start + max_len] # 测试示例 s1 = "babad" print(longestPalindromeDP(s1)) # 输出:"aba" s2 = "jbbjaa" print(longestPalindromeDP(s2))

  

posted @ 2024-03-24 15:23  bonelee  阅读(10)  评论(0编辑  收藏  举报