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:
2
One possible longest palindromic subsequence is "bb".
和5、647两个题不一样,这个题的回文允许跳跃。
AC代码:
class Solution {
public:
int longestPalindromeSubseq(string s) {
int i,j,len=s.size();
vector<vector<int>> dp(len,vector<int>(len,0));//treated as a 2-d array
for(i=len-1;i>=0;i--){
dp[i][i]=1;//single character
for(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];
}
};
如果头和尾相等,那么等于去掉头尾的子串长度加上2,否则等于去掉头的子串或者去掉尾的子串中最大的那个。