b_lc_由子序列构造的最长回文串的长度(拼接+特判)

从 word1 中选出某个 非空 子序列 subsequence1 。
从 word2 中选出某个 非空 子序列 subsequence2 。
连接两个子序列 subsequence1 + subsequence2 ,得到字符串。
返回可按上述方法构造的最长 回文串 的 长度

思路:f[i][j]表示s[i:j]中的最长回文子序列的长度

class Solution:
    def longestPalindrome(self, word1: str, word2: str) -> int:
        s, n, len1 = word1 + word2, len(word1) + len(word2), len(word1)
        f, ans = [[0]*n for _ in range(n)], 0
        for i in range(n-1,-1,-1):
            f[i][i] = 1
            for j in range(i+1,n):
                if s[i] == s[j]: 
                    f[i][j] = f[i+1][j-1] + 2
                    if i < len1 and j >= len1 and f[i][j] > ans::
                        ans = f[i][j]
                else: 
                    f[i][j] = max(f[i+1][j], f[i][j-1])
        return ans

区间dp也可以求解

class Solution:
    def longestPalindrome(self, word1: str, word2: str) -> int:
        s, n, len1 = word1 + word2, len(word1) + len(word2), len(word1)
        f, ans = [[0]*n for _ in range(n)], 0
        for i in range(n): f[i][i] = 1
        for ln in range(2,n+1):
            for l in range(n-ln+1):
                r = l + ln - 1
                if s[l] == s[r]:
                    f[l][r] = f[l+1][r-1] + 2
                    if l < len1 and r >= len1 and f[l][r] > ans:
                        ans = f[l][r]
                else:
                    f[l][r] = max(f[l+1][r], f[l][r-1])
        return ans
posted @ 2021-02-21 16:51  童年の波鞋  阅读(64)  评论(0编辑  收藏  举报