I'm trying to solve this problem using the same concept of Longest Palindromic Subsequence. I'm not working with a single-value state but I'm using 2-values state, because we have to maximize the number of special characters and the palindrome length.
I'm using a struct to represent each state, as follows.
Code: Select all
struct state {
int len, spec;
state() {}
state(int _len, int _spec) : len(_len), spec(_spec) {}
bool operator < (const state &than) const {
if (spec < than.spec) return true;
else if (spec == than.spec) return len < than.len;
else return false;
}
};
- spec: Represents how many special characters I am including in the current state palindrome.
Notice how the bool operator < function maximizes first by number of special characters and then by length.
Our function looks like this:
Code: Select all
state
lps(const string &seq, int i, int j) { ... }
Base case 1: If there is only one character, that character is a palindrome itself, and if it is a special character our spec attribute should be 1, or 0 otherwise.
Code: Select all
if (i == j) return state(1, is_spec[i]);
Base case 2: If there are only 2 characters and both are the same, the length of the palindrome is 2 and we add each special character.
Code: Select all
if (seq[i] == seq[j] && i + 1 == j) return state(2, is_spec[i] + is_spec[j]);
Code: Select all
if (seq[i] == seq[j]) {
state ret = lps(seq, i + 1, j - 1);
ret.len += 2;
ret.spec += (is_spec[i] + is_spec[j]);
return ret;
}
Code: Select all
if (seq[i] != seq[j]) return max(lps(seq, i, j - 1), lps(seq, i + 1, j));
Code: Select all
lps(seq, 0, seq.size() - 1).len
Thanks a lot.