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".
Subscribe to see which companies asked this question.
思路
题目需要字符串s中最长的回文子串。动态规划的思想,设l[i][j]表示字符串s中下标i到j的子串中的最长回文串,若子串的两边各增加一个字符,求l[i-1][j+1]时,若s[i-1]=sj[j+1],则找到了一个更长的回文,长度为l[i][j]+2,反之,子串中最长的回文串是l[i][j+1]和l[i-1][j]中的最大值。
源码
class Solution {
public:
int longestPalindromeSubseq(string s) {
int l[1001][1001];
int i,j;
int len = s.length();
for(i = 0;i < len;i ++)
l[i][i] = 1;
for(i = len - 2;i >= 0;i --){
for(j = i + 1;j < len;j ++){
if(s[i] == s[j])
l[i][j] = l[i + 1][j -1] + 2;
else
l[i][j] = max(l[i][j - 1],l[i + 1][j]);
}
}
return l[0][len - 1];
}
};