Longest-Palindromic-Subsequence

题目地址

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
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int longestPalindromeSubseq(string s) {
vector<vector<int>> dp(s.size() , vector<int>(s.size() , 0));
for(int i = s.size() - 1 ; i >= 0 ; --i){
dp[i][i] = 1;
for (int j = i+1; j < s.size(); ++j) {
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][s.size()-1];
}
};
0%