Given a sequence, print a longest palindromic subsequence of it.
Input : BBABCBCAB Output : BABCBAB The above output is the longest palindromic subsequence of given sequence. "BBBBB" and "BBCBB" are also palindromic subsequences of the given sequence, but not the longest ones. Input : GEEKSFORGEEKS Output : Output can be either EEKEE or EESEE or EEGEE, ..
We have discussed a solution in below post to find length of longest palindromic subsequence.
Dynamic Programming | Set 12 (Longest Palindromic Subsequence)
In this post a solution to print the longest palindromic subsequence is discussed.
This problem is close to the Longest Common Subsequence (LCS) problem. In fact, we can use LCS as a subroutine to solve this problem. Following is the two step solution that uses LCS.
1) Reverse the given sequence and store the reverse in another array say rev[0..n-1]
2) LCS of the given sequence and rev will be the longest palindromic sequence.
3) Once we have found LCS, we can print the LCS.
Below is the implementation of above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Longest Palindromic Subsequence | DP-12
- Longest Palindromic Subsequence of two distinct characters
- Print the longest palindromic prefix of a given string
- Length of longest Palindromic Subsequence of even length with no two adjacent characters same
- Print all Longest dividing subsequence in an Array
- Longest Increasing Subsequence using Longest Common Subsequence Algorithm
- Count All Palindromic Subsequence in a given String
- Smallest Palindromic Subsequence of Even Length in Range [L, R]
- Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime
- Find the lexicographically largest palindromic Subsequence of a String
- Longest Non-palindromic substring
- Longest Palindromic Substring | Set 2
- Longest Palindromic Substring | Set 1
- Longest palindromic string possible after removal of a substring
- Length of longest palindromic sub-string : Recursion
- Longest palindromic String formed using concatenation of given strings in any order
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 2
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 4
This article is contributed by Kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.