Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"
Output:
2
One possible longest palindromic subsequence is "bb".
题解:求最长回文子序列
动态规划思想:
- 对于任意字符串,如果头尾字符相同,那么字符串的最长子序列等于去掉首尾的字符串的最长子序列加上d首尾;
- 如果首尾字符不同,则最长子序列等于去掉头的字符串的最长子序列和去掉尾的字符串的最长子序列的较大者。
动态规划的状态转移方程为:
- 设字符串为str,长度为n,dp[i][j]表示第i到第j个字符间的子序列的个数(i<=j),则:
- 状态初始条件:dp[i][i]=1,(i=0: n-1)
- 状态转移方程:dp[i][j]=dp[i+1][j-1] + 2 if(str[i]==str[j]);dp[i][j]=max(dp[i+1][j],dp[i][j-1]) if (str[i]!=str[j])
class Solution: def longestPalindromeSubseq(self, s: str) -> int: m = len(s) # dp = [[0 for _ in range(m)] for _ in range(m)] dp = [[0] * m for _ in range(m)] for i in range(m-1, -1, -1): dp[i][i] = 1 for j in range(i+1, m): if s[i] == s[j]: dp[i][j] = dp[i+1][j-1] + 2 else: dp[i][j] = max(dp[i+1][j], dp[i][j-1]) return dp[0][m-1]