Caută
  • oanaunciuleanu

Longest common subsequence algorithm in C++


Having two strings, you have to find the longest common subsequence. This means that you have to find how many letters are found in both strings, in the same order, and not necessarily adjacent. For example, the string CALENDAR and CABLNDR have as the longest common subsequence CALNDR. The letters are spread along the two strings but are found in the same order.


// Longest common subsequence algorithm
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;

int longestCommonSubsequence( char *firstString, char *secondString, int lengthOfFirstString, int lengthOfSecondString)
{
   int lengthStrings[lengthOfFirstString + 1][lengthOfSecondString + 1];

   for (int i = 0; i <= lengthOfFirstString; i++)
   {
     for (int j = 0; j <= lengthOfSecondString; j++)
     {
       if (i == 0 || j == 0)
       {
           lengthStrings[i][j] = 0;
       }
       else if (firstString[i-1] == secondString[j-1])
       {
           lengthStrings[i][j] = lengthStrings[i-1][j-1] + 1;
       }
       else
       {
           lengthStrings[i][j] = max(lengthStrings[i-1][j], lengthStrings[i][j-1]);
       }
     }
   }

   int lengthLCS = lengthStrings[lengthOfFirstString][lengthOfSecondString];
   int index = lengthStrings[lengthOfFirstString][lengthOfSecondString];

   char longestCommonSubseq[index + 1];
   longestCommonSubseq[index] = '\0';

   int i = lengthOfFirstString;
   int j = lengthOfSecondString;

   while (i > 0 && j > 0)
   {
      if (firstString[i - 1] == secondString[j - 1])
      {
          longestCommonSubseq[index - 1] = firstString[i - 1];
          i--;
          j--;
          index--;
      }
      else if (lengthStrings[i - 1][j] > lengthStrings[i][j - 1])
      {
          i--;
      }
      else
      {
           j--;
      }
   }
   cout << "Longest Common Subsequence of " << firstString << " and " << secondString << " is " << longestCommonSubseq << " with length: " << lengthLCS << endl;
}

int main()
{
  char firstString[] = "CALENDAR";
  char secondString[] = "CABLNDR";
  int lengthOfFirstString = strlen(firstString);
  int lengthOfSecondString = strlen(secondString);
  longestCommonSubsequence(firstString, secondString, lengthOfFirstString, lengthOfSecondString);
  return 0;
}


Longest   Common Subsequence of CALENDAR and CABLNDR is CALNDR with length: 6

© 2018 by The Art Of Coding. by Oana Unciuleanu

This site was designed with the
.com
website builder. Create your website today.
Start Now