Here we have two solutions.
Both are DP.
The first solution is quite smart and difficult to think of.
Basically, you just need to reverse the string, and then find the longest common subsequence.
The reason is a palindromic string is the same as it is reversed. So, we just need to reverse the string and find the longest common subsequence that is the answer we needed.
class Solution {
public:
int longestCommonSubsequence(string &a, string &b) {
short m[2][10000] = {};
for (int i = 0; i < a.size(); ++i)
for (int j = 0; j < b.size(); ++j)
m[!(i % 2)][j + 1] = a[i] == b[j] ? m[i % 2][j] + 1 : max(m[i % 2][j + 1], m[!(i % 2)][j]);
return m[a.size() % 2][b.size()];
}
int longestPalindromeSubseq(string s) {
string x = s;
reverse(s.begin(), s.end());
return longestCommonSubsequence(x, s);
}
};
The second method is quite intuitive. We consider the DP array as a certain interval that has the longest palindrome.
DP[i][j] represents the longest length of the palindrome subsequence between intervals i to j.
The equation is easy to think of because the larger interval relies on the smaller interval which is dp[i + 1][j - 1].
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n));
for (int i = n - 1; i >= 0; --i) {
dp[i][i] = 1;
for (int j = i+1; j < n; ++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][n-1];
}
};