当前位置:   article > 正文

LeetCode题解(1682):最长回文子序列II(Python)_最长回文子序列2

最长回文子序列2

题目:原题链接(中等)

标签:动态规划、字符串

解法时间复杂度空间复杂度执行用时
Ans 1 (Python) O ( 26 × N 2 ) O(26×N^2) O(26×N2) O ( 26 × N 2 ) O(26×N^2) O(26×N2)4752ms (38.46%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        size = len(s)

        # dp[i][j] = 令字符串[i,j]变为回文串需要删除的字符数
        dp = [[[0] * 26 for _ in range(size)] for _ in range(size)]

        for length in range(2, size + 1):
            for i in range(size - length + 1):
                j = i + length - 1
                if s[i] == s[j]:
                    a = ord(s[i]) - 97
                    for k in range(26):
                        dp[i][j][k] = max(dp[i][j][k], dp[i + 1][j - 1][k])
                        if k != a:
                            dp[i][j][a] = max(dp[i][j][a], dp[i + 1][j - 1][k] + 1)
                            # print(i + 1, j - 1, k, "->", i, j, a, "=", dp[i][j][a])
                    # print(i, j, a, ":", dp[i][j][a])
                else:
                    for k in range(26):
                        dp[i][j][k] = max(dp[i + 1][j][k], dp[i][j - 1][k])

        return max(dp[0][-1]) * 2
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/590374
推荐阅读
相关标签
  

闽ICP备14008679号