Length of longest Palindromic Subsequence of even length with no two adjacent characters same
Given a string str, the task is to find the length of the longest palindromic subsequence of even length with no two adjacent characters same except the middle characters.
Input: str = “abscrcdba”
abccba is the required string which has no two consecutive characters same except the middle characters. Hence the length is 6
Input: str = “abcd”
Approach: The idea is to form a recursive solution and store the values of the subproblems using Dynamic Programming. The following steps can be followed to compute the result:
- Form a recursive function which will take a string and a character which is the starting character of the subsequence.
- If the first and last character of the string matches with the given character then remove the first and last character and call the function with all the character values from ‘a’ to ‘z’ except the given character, as the adjacent character cannot be same and find the maximum length.
- If the first and last character of the string does not match with the given character, then find the first and last index of the given character in the string, say i, j respectively. Take the substring from i to j and call the function with substring and the given character.
- Finally, memorise the values in an unordered map and use it if the function is again called with the same parameters.
The following is the implementation of the above approach:
Time Complexity: O(N2)
Auxiliary Space: O(N)
Related Article: Longest Palindromic Subsequence