题目地址
LeetCode#516 Longest Palindromic Subsequence
题目描述
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:
1 | "bbbab" |
Output:
1 | 4 |
One possible longest palindromic subsequence is “bbbb”.
Example 2:
Input:
1 | "cbbd" |
Output:
1 | 2 |
One possible longest palindromic subsequence is “bb”.
解题思路
最长回文子序列,和最长回文字符串不同的地方在于这个不要求连续,做法和最长回文字符串也不差多少。我们使用 DP ,递推公式如下:
- s[i] == s[j] : dp[i][j] = dp[i+1][j-1] + 2
- s[i] != s[j] : dp[i][j] = max(dp[i+1][j] , dp[i][j-1])
解题代码【.CPP】
1 | class Solution { |