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:
Related Article: Longest Palindromic Subsequence
- Length of the longest subsequence such that xor of adjacent elements is non-decreasing
- Length of the longest increasing subsequence such that no two adjacent elements are coprime
- Maximum length subsequence such that adjacent elements in the subsequence have a common factor
- Length of longest palindromic sub-string : Recursion
- Maximum length subsequence with difference between adjacent elements as either 0 or 1
- Length of Longest Balanced Subsequence
- Find length of longest Fibonacci like subsequence
- Length of Longest Prime Subsequence in an Array
- Length of longest strict bitonic subsequence
- Length of longest common subsequence containing vowels
- Length of longest subsequence of Fibonacci Numbers in an Array
- Minimum cost to make Longest Common Subsequence of length k
- Length of the longest substring without repeating characters
- Minimum length of the sub-string whose characters can be used to form a palindrome of length K
- Find length of longest subsequence of one string which is substring of another string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.