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:
“bbbab”
Output:
4
One possible longest palindromic subsequence is “bbbb”.
Example 2:
Input:
“cbbd”
Output:
2
One possible longest palindromic subsequence is “bb”.
分析
按长度来更新dp数组,
if(s[j]==s[j+len-1])
dp[j][j+len-1]=dp[j+1][j+len-2]+2;
else
dp[j][j+len-1]=max(dp[j+1][j+len-1],dp[j][j+len-2]);
class Solution {
public:
int longestPalindromeSubseq(string s) {
vector<vector<int>> dp(s.size(),vector<int>(s.size(),0));
for(int i=0;i<s.size();i++)
dp[i][i]=1;
for(int len=2;len<=s.size();len++)
for(int j=0;j<=s.size()-len;j++)
if(s[j]==s[j+len-1])
dp[j][j+len-1]=dp[j+1][j+len-2]+2;
else
dp[j][j+len-1]=max(dp[j+1][j+len-1],dp[j][j+len-2]);
return dp[0][s.size()-1];
}
};