Search Tutorials

Friday, 12 June 2015

Longest Common Sub-sequence (LCS) Using C++

The longest common sub-sequence (LCS) problem is the problem of finding the longest sub-sequence common to all sequences in a set of sequences (often just two sequences). It differs from problems of finding common sub-strings: unlike sub-strings, sub-sequences are not required to occupy consecutive positions within the original sequences. The longest common sub-sequence problem is a classic computer science problem, the basis of data comparison programs such as the diff utility, and has applications in bioinformatics. It is also widely used by revision control systems such as Git for reconciling multiple changes made to a revision-controlled collection of files.

// C++ Program to implement Longest Common Sub-sequence(LCS).

#include<iostream>

using namespace std;

int strlen(char []);
int max(int a, int b);

int lcs( char *X, char *Y, int m, int n )
{
   if (m == 0 || n == 0)
     return 0;
   if ((X[m] == Y[n])&&(m>0&&n>0))
     return 1 + lcs(X, Y, m-1, n-1);
   else
     return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}

int max(int a, int b)
{
    if(a>b)
    {
        return a;
    }
    else
    {
        return b;
    }
}

int strlen(char s[])
{
     int p;
     for(p=1; s[p]!='\0'; p++);
     return p;
}

int main()
{
  char X[] = "abcbdab";
  char Y[] = "bdcaba";

  int m = strlen(X);
  cout<<endl<<"Length of X[] is = "<<m<<endl;
  int n = strlen(Y);
  cout<<endl<<"Length of Y[] is = "<<n<<endl;

  cout<<endl<<"Length of LCS is = "<<lcs( X, Y, m, n )<<endl;
  return 0;
}

// Output of the above program.

12 comments:

  1. Can you print the subsequence ?

    ReplyDelete
  2. Can u provide me the code for printing LCS of sequence of integer number

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This is so needful article.thanks for sharing with us.

    ReplyDelete
  5. It was an amazing article.Thanks a lot for sharing this

    ReplyDelete
  6. Thanks for sharing this blog its very informative
    clipping path
    Raster To vector

    ReplyDelete
  7. Thank you for your useful and educative post . I liked it guy . Clipping Path | Remove White Background | Product Photo Editing

    ReplyDelete
  8. This articles and tutorial is very closed and helpful for web designer and i'm graphic designer which is almost similar profession. I do provide Raster to Vector Conversion Service

    ReplyDelete
  9. Very comprehensive writing. It starts slowly but after a certain time you are bound to put yourselves in. clipping path service company

    ReplyDelete
  10. I am happy to find your distinguished way of writing the post.
    Now you make it easy for me to understand and implement the concept. Thank you for the post. Photo Background Removal

    ReplyDelete

Back to Top