Leetcode 516.最长回文子序列( Longest Palindromic Subsequence)

Leetcode 516.最长回文子序列

1 题目描述(Leetcode题目链接

  给定一个字符串s,找到其中最长的回文子序列。可以假设s的最大长度为1000。示例:
输入:

"bbbab"

输出:

4

2 题解

  本题是动态规划问题,分析题目可知,一个字符串s的最长回文子序列可以通过两种情况得到(注意子序列可以由不连续的字符构成):

  1. 如果首字符和尾字符相等,则字符串s的最长回文子序列为2加上去除这两个字符的字符串的最长回文子序列;
  2. 如果首字符和尾字符不相等,则字符串s的最长回文子序列为去掉两个字符之一的两个字符串的最长回文子序列之间的最大值。

因此可以定义 D P [ i ] [ j ] DP[i][j] 为第 i i 个字符到第 j j 个字符的最长回文子序列,可以写为:
D P = { 2 + D P [ i + 1 ] [ j 1 ] i f s [ i ] = s [ j ] m a x ( D P [ i + 1 ] [ j ] , D P [ i ] [ j 1 ] ) o t h e r w i s e DP = \begin{cases}2+DP[i+1][j-1] &&if&s[i]=s[j]\\max(DP[i+1][j],DP[i][j-1]) &&&otherwise\end{cases}
初始化 D P DP 为单位矩阵,即 D P [ i ] [ i ] = 1 DP[i][i] = 1 ,其余元素为0。

class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        length = len(s)
        if length <= 1:
            return length
        DP = [([0]*length) for i in range(length)]
        for i in range(0,length):   //初始化
            DP[i][i] = 1 
        i = length-2
        while i >= 0:
            for j in range(i+1, length):
                if s[i] == s[j]:
                    DP[i][j] = 2 + DP[i+1][j-1]
                else:
                    DP[i][j] = max(DP[i+1][j],DP[i][j-1])
            i -= 1
        return DP[0][length - 1] 
发布了32 篇原创文章 · 获赞 53 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_39378221/article/details/104045964