Longest Palindromic Subsequence of two distinct characters

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.
Examples: 

Input: S = “bbccdcbb” 
Output:
Explanation: 
The longest palindromic subsequence of the desired form is “bbcccbb”, which is of length 7.
Input: S = “aeea” 
Output:
Explanation: 
The longest palindromic subsequence of desired form is “aeea”, which is of length 4. 

Approach: 
In order to solve the problem, we need to follow the steps below:  

Below is the implementation of the above approach:
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find Longest
// Palindromic Subsequence consisting
// of two distinct characters only
 
#include <bits/stdc++.h>
using namespace std;
 
// Function that prints the length of
// maximum required subsequence
void longestPalindrome(string s)
{
    // Calculate length of string
    int n = s.length();
 
    vector<vector<int> > pref(
        26,
        vector<int>(n, 0));
    vector<vector<int> > pos(26);
 
    pref[s[0] - 'a'][0]++;
    pos[s[0] - 'a'].push_back(0);
 
    // Store number of occurrences of each
    // character and position of each
    // chatacter in string
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < 26; j++)
            pref[j][i] += pref[j][i - 1];
 
        int index = s[i] - 'a';
        pref[index][i]++;
        pos[index].push_back(i);
    }
 
    int ans = 0;
 
    // Iterate all characters
    for (int i = 0; i < 26; i++) {
 
        // Calculate number of
        // occurences of the
        // current character
        int size = pos[i].size();
        ans = max(ans, size);
 
        // Iterate half of the
        // number of positions
        // of current character
        for (int j = 0; j < size / 2; j++) {
            int l = pos[i][j];
            int r = pos[i][size - j - 1] - 1;
 
            // Determine maximum length
            // of a character between
            // l and r position
            for (int k = 0; k < 26; k++) {
 
                int sum = pref[k][r] - pref[k][l];
 
                // Compute the maximum from all
                ans = max(ans, 2 * (j + 1) + sum);
            }
        }
    }
 
    // Printing maximum length
    cout << ans << "\n";
}
 
// Driver Code
int main()
{
    string S = "bbccdcbb";
 
    longestPalindrome(S);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find Longest
// Palindromic Subsequence consisting
// of two distinct characters only
import java.util.*;
class GFG{
 
// Function that prints the length of
// maximum required subsequence
static void longestPalindrome(String s)
{
  // Calculate length of String
  int n = s.length();
 
  int [][]pref = new int[26][n];
 
  Vector<Integer> []pos = new Vector[26];
  for (int i = 0; i < pos.length; i++)
    pos[i] = new Vector<Integer>();
 
  pref[s.charAt(0) - 'a'][0]++;
  pos[s.charAt(0) - 'a'].add(0);
 
  // Store number of occurrences of each
  // character and position of each
  // chatacter in String
  for (int i = 1; i < n; i++)
  {
    for (int j = 0; j < 26; j++)
      pref[j][i] += pref[j][i - 1];
 
    int index = s.charAt(i) - 'a';
    pref[index][i]++;
    pos[index].add(i);
  }
 
  int ans = 0;
 
  // Iterate all characters
  for (int i = 0; i < 26; i++)
  {
    // Calculate number of
    // occurences of the
    // current character
    int size = pos[i].size();
    ans = Math.max(ans, size);
 
    // Iterate half of the
    // number of positions
    // of current character
    for (int j = 0; j < size / 2; j++)
    {
      int l = pos[i].elementAt(j);
      int r = pos[i].elementAt(size - j - 1) - 1;
 
      // Determine maximum length
      // of a character between
      // l and r position
      for (int k = 0; k < 26; k++)
      {
        int sum = pref[k][r] - pref[k][l];
 
        // Compute the maximum from all
        ans = Math.max(ans, 2 *
                      (j + 1) + sum);
      }
    }
  }
 
  // Printing maximum length
  System.out.print(ans + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
  String S = "bbccdcbb";
  longestPalindrome(S);
}
}
 
// This code is contributed by Princi Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find longest
// Palindromic Subsequence consisting
// of two distinct characters only
using System;
using System.Collections.Generic;
class GFG{
 
// Function that prints
// the length of maximum
// required subsequence
static void longestPalindrome(String s)
{
  // Calculate length of String
  int n = s.Length;
 
  int [,]pref = new int[26, n];
  List<int> []pos = new List<int>[26];
   
  for (int i = 0; i < pos.Length; i++)
    pos[i] = new List<int>();
 
  pref[s[0] - 'a', 0]++;
  pos[s[0] - 'a'].Add(0);
 
  // Store number of occurrences of each
  // character and position of each
  // chatacter in String
  for (int i = 1; i < n; i++)
  {
    for (int j = 0; j < 26; j++)
      pref[j, i] += pref[j, i - 1];
 
    int index = s[i] - 'a';
    pref[index, i]++;
    pos[index].Add(i);
  }
 
  int ans = 0;
 
  // Iterate all characters
  for (int i = 0; i < 26; i++)
  {
    // Calculate number of
    // occurences of the
    // current character
    int size = pos[i].Count;
    ans = Math.Max(ans, size);
 
    // Iterate half of the
    // number of positions
    // of current character
    for (int j = 0; j < size / 2; j++)
    {
      int l = pos[i][j];
      int r = pos[i][size -
                     j - 1] - 1;
 
      // Determine maximum length
      // of a character between
      // l and r position
      for (int k = 0; k < 26; k++)
      {
        int sum = pref[k, r] -
                  pref[k, l];
 
        // Compute the maximum from all
        ans = Math.Max(ans, 2 *
                      (j + 1) + sum);
      }
    }
  }
 
  // Printing maximum length
  Console.Write(ans + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
  String S = "bbccdcbb";
  longestPalindrome(S);
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Output: 

7






 

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.




My Personal Notes arrow_drop_up

Interns at Geeksforgeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.