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".
思路:相当于找这个字符串与其反转的最长公共子序列
代码:
class Solution {
public:
int longestPalindromeSubseq(string s) {
string t = s;
reverse(s.begin(),s.end());
return lcs(t,s);
}
int lcs(string t, string s){
int m = t.size(), n = s.size();
vector<vector<int>>dp(n+1,vector<int>(m+1,0));
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
if(s[i-1] == t[j-1])
dp[i][j] = dp[i-1][j-1]+1;
}
}
return dp[n][m];
}
};