题目:
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:
4One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"Output:
2One possible longest palindromic subsequence is "bb".
动态规划问题,但是没用动态规划的方法,用了map的方法,存进map然后遍历map,比O(n2)的方法稍微好了一点。但最差也是O(n2)。
想不到如何用动态规划的方法,直接看了别人的解析:
The DP state longest[i][j] means for substring between [i, j] inclusive the longest palindromic subsequence.
Basic cases:
if i == j, then longest[i][j] = 1, naturally
if i+1 == j, then longest[i][j] = 2 if s[i] == s[j]
longest[i][j] = 1 otherwise
Transition rule:
- s[i] == s[j]
dp[i][j] = max(dp[i+1][j], dp[i][j-1], dp[i+1][j-1] + 2) - s[i] != s[j]
dp[i][j] = max(dp[i+1][j], dp[i][j-1], dp[i+1][j-1])
The condition that only subsequence made it quite simply because at any range [i, j], the s[i], s[j] can be omitted to make the rest range [i+1, j] or [i, j-1] our valid longest palindromic subsequence.
自己的代码:class Solution {
public:
int longestPalindromeSubseq(string s) {
map<char, int> mymap;
for(int i = 0;i < s.size(); ++i){
if(mymap.count(s[i]) != 0){
mymap[s[i]] += 1;
}
else mymap[s[i]] = 1;
}
map<char, int>::iterator it;
int max = 0;
for(it = mymap.begin(); it != mymap.end(); it++){
if(it->second > max){
max = it->second;
}
}
return max;
}
};