A subsequence of a string s is considered a good palindromic subsequence if:
It is a subsequence of s.
It is a palindrome (has the same value if reversed).
It has an even length.
No two consecutive characters are equal, except the two middle ones.
For example, if s = "abcabcabb", then "abba" is considered a good palindromic subsequence , while "bcb" (not even length) and "bbbb" (has equal consecutive characters) are not.
Given a string s, return _thelength of the longest good palindromic subsequence in _s.
The key idea is to use dynamic programming to find the longest even-length palindromic subsequence with no consecutive equal characters (except the middle two). We try all possible pairs of characters for the ends and recursively solve for the inner substring, ensuring the constraints are met.
classSolution {
public:int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<vector<int>>> dp(n, vector<vector<int>>(n, vector<int>(26, 0)));
int ans =0;
for (int len =2; len <= n; ++len) {
for (int l =0; l + len -1< n; ++l) {
int r = l + len -1;
for (int ch =0; ch <26; ++ch) {
if (s[l] -'a'== ch && s[r] -'a'== ch) {
if (len ==2) dp[l][r][ch] =2;
else {
for (int mid =0; mid <26; ++mid) {
if (mid != ch) dp[l][r][ch] = max(dp[l][r][ch], dp[l+1][r-1][mid] +2);
}
}
}
ans = max(ans, dp[l][r][ch]);
}
}
}
return ans;
}
};
classSolution {
funlongestPalindromeSubseq(s: String): Int {
val n = s.length
val dp = Array(n) { Array(n) { IntArray(26) } }
var ans = 0for (len in2..n) {
for (l in0..n-len) {
val r = l + len - 1for (ch in0..25) {
if (s[l] - 'a'== ch && s[r] - 'a'== ch) {
if (len ==2) dp[l][r][ch] = 2else {
for (mid in0..25) {
if (mid != ch) dp[l][r][ch] = maxOf(dp[l][r][ch], dp[l+1][r-1][mid] + 2)
}
}
}
ans = maxOf(ans, dp[l][r][ch])
}
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
deflongestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [[[0]*26for _ in range(n)] for _ in range(n)]
ans =0for length in range(2, n+1):
for l in range(n-length+1):
r = l + length -1for ch in range(26):
if ord(s[l])-ord('a') == ch and ord(s[r])-ord('a') == ch:
if length ==2:
dp[l][r][ch] =2else:
for mid in range(26):
if mid != ch:
dp[l][r][ch] = max(dp[l][r][ch], dp[l+1][r-1][mid]+2)
ans = max(ans, dp[l][r][ch])
return ans
impl Solution {
pubfnlongest_palindrome_subseq(s: String) -> i32 {
let n = s.len();
let s = s.as_bytes();
letmut dp =vec![vec![vec![0; 26]; n]; n];
letmut ans =0;
for len in2..=n {
for l in0..=n-len {
let r = l + len -1;
for ch in0..26 {
if s[l] -b'a'== ch asu8&& s[r] -b'a'== ch asu8 {
if len ==2 {
dp[l][r][ch] =2;
} else {
for mid in0..26 {
if mid != ch {
dp[l][r][ch] = dp[l][r][ch].max(dp[l+1][r-1][mid] +2);
}
}
}
}
ans = ans.max(dp[l][r][ch]);
}
}
}
ans asi32 }
}