题目
Given a string s, find the longest palindromic subsequence’s length in s.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: s = “bbbab”
Output: 4
Explanation: One possible longest palindromic subsequence is “bbbb”.
Example 2:
Input: s = “cbbd”
Output: 2
Explanation: One possible longest palindromic subsequence is “bb”.
Constraints:
1 <= s.length <= 1000
s consists only of lowercase English letters.
代码
class Solution {
public:
int longestPalindromeSubseq(string s) {
string::size_type len = s.size();
if(len < 1)
return 0;
vector<vector<int>> dp(len, vector<int>(len));
for(int i = 0; i<len; i++)
dp[i][i] = 1;
for(int i = len-1; i>=0; i--){
for(int j = i+1; j<len; 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][len-1];
}
};
一次AC again!是题目太简单还是哈哈哈哈哈 ^ ______________________________ ^