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".
翻译:
给定一个字符串s,找到最长的回文子序列长度。 您可以假设s的最大长度为1000。
示例1:
输入:
“bbbab”
输出:
4
一个可能最长的回文序列是“bbbb”。
示例2:
输入:
“cbbd”
输出:
2
一个可能最长的回文序列是“bb”。
解题代码:
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
class Solution {
public:
int longestPalindromeSubseq(string s) {
int arr[s.length()][s.length()] = {0};
for(int len = 1 ;len <= s.length(); len++) {
for(int l = 0; l + len <=s.length();l++) {
int r = l+len-1;
if(l == r) arr[l][r] == 1;
else if(l + 1 == r) arr[l][r]= s[l]==s[r]?2:1;
else {
int attach = s[l] == s[r]?2:0;
arr[l][r] = max( max(arr[l][r-1],arr[l+1][r]),arr[l+1][r-1]+attach);
}
}
}
return arr[0][s.length()-1];
}
};
int main() {
string s = "bbbab";
Solution tem;
cout << tem.longestPalindromeSubseq(s) <<endl;
}
题目状态: