Given a string S of lowercase letters, the task is to find the length of the longest palindromic subsequence made up of two distinct characters only.
Input: S = “bbccdcbb”
The longest palindromic subsequence of the desired form is “bbcccbb”, which is of length 7.
Input: S = “aeea”
The longest palindromic subsequence of desired form is “aeea”, which is of length 4.
In order to solve the problem, we need to follow the steps below:
- Store the number of occurrences of each character in a prefix array, and also store the position of each character in another array.
- Now for each pair of equal characters calculate the maximum number of occurrences of a character between them.
Below is the implementation of the 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.
- Length of longest Palindromic Subsequence of even length with no two adjacent characters same
- Longest Palindromic Substring using Palindromic Tree | Set 3
- Longest Palindromic Subsequence | DP-12
- Print Longest Palindromic Subsequence
- Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime
- Length of the longest subsequence consisting of distinct elements
- Find distinct characters in distinct substrings of a string
- Make palindromic string non-palindromic by rearranging its letters
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Longest subsequence with different adjacent characters
- String with k distinct characters and no same characters adjacent
- Replace minimal number of characters to make all characters pair wise distinct
- Count of ungrouped characters after dividing a string into K groups of distinct characters
- Longest substring with atmost K characters from the given set of characters
- Find the lexicographically largest palindromic Subsequence of a String
- Smallest Palindromic Subsequence of Even Length in Range [L, R]
- Check if an array has some palindromic subsequence of length at least 3
- Count All Palindromic Subsequence in a given String
- Find all distinct palindromic sub-strings of a given string
- Generate a String of having N*N distinct non-palindromic Substrings
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.