516. Longest Palindromic Subsequence
- Total Accepted: 9935
- Total Submissions: 23475
- Difficulty: Medium
- Contributors:
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".
Subscribe to see which companies asked this question.
Show Similar Problems
思路:
设字符串中从i到j中回文子序列的最长长度为length(i,j),由回文子序列的性质可得,如果s[i] = s[j]且i+1 <= j-1,length(i,j)=length(i+1,j-1)+ 2;而s[i] = s[j]且i+1 > j-1,length(i,j)= 2;若s[i] != s[j]则length(i,j)= max(length(i+1,j),length(i,j-1))。所以该字符串中回文子序列的最长长度为length(0,s.size() - 1)。
代码:
class Solution {
public:
int longestPalindromeSubseq(string s) {
int size = s.size();
int num = 1;
vector
> length(size, vector
(size, 1));
for(int i = 1; i < size; i ++){
for(int j = i - 1; j >= 0; j --){
if(s[i] == s[j]){
if(j + 1 <= i - 1) length[j][i] = length[j + 1][i - 1] + 2;
else length[j][i] = 2;
}
else{
length[j][i] = max(length[j + 1][i], length[j][i - 1]);
}
}
}
return length[0][size - 1];
}
};