Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Longest Common Subsequence Length function not returning the correct length?

Tags:

c++

algorithm

I have attempted to implement the dynamic programming approach to finding the longest common sub sequence between two sequences. My algorithm works when the two strings that are being compared are the same lengths, but when the second string is longer than the first, my LCSLength() function does not return the correct value.

Here is code with a test case that returns the wrong value.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int LCSLength(string X,string Y);

int main()
{
    string first ("HELLO");
    string second ("HLOCKKE");
    int LCS;

    //ifstream inData;
    //inData.open("test.dat");

    //inData >> first >> second;
    //inData.close();

    LCS = LCSLength(first,second);
    cout << "The LCS is: " << LCS << endl;
    cout << first << endl;
    cout << second << endl;
    return 0;
}

int LCSLength(string X,string Y)
{
    int m = X.size();
    int n = Y.size();
    int C[m][n];
    for(int i=0; i<=m; i++)
    {
        for(int j=0; j<=n; j++)
            C[i][j] = 0;
    }
    for(int i=1; i<=m; i++)
    {
        for(int j=1; j<=n; j++)
        {
            if(X[i-1]==Y[j-1])
                C[i][j]=C[i-1][j-1]+1;
            else 
                C[i][j]=max(C[i][j-1],C[i-1][j]);
       }
    }

    return C[m][n];
}

This should print "The LCS is: 3" because the LCS between my two strings is 3, however, my program does not. I can't find my error. Thank you for your help.

like image 604
Zack Avatar asked Jun 18 '26 13:06

Zack


1 Answers

Fixed my errors using some google searches. Indexing was my problem. Here is the correct code:

#include <iostream>
#include <string>
#include <fstream>


using namespace std;

int LCSLength(string X,string Y);

int main()
{
    string first ("HELLO");
    string second ("HLOCKKE");
    int LCS;

    //ifstream inData;
    //inData.open("test.dat");

    //inData >> first >> second;
    //inData.close();

    LCS = LCSLength(first,second);
    cout << "The LCS is: " << LCS << endl;
    cout << first << endl;
    cout << second << endl;
    return 0;
}

int LCSLength(string X,string Y)
{
    int m = X.size();
    int n = Y.size();
    int L[m+1][n+1];
    for(int i=0; i<=m; i++)
    {
        for(int j=0; j<=n; j++)
        {
            if(i==0 || j==0)
                L[i][j] = 0;
            else if(X[i-1]==Y[j-1])
                L[i][j] = L[i-1][j-1]+1;
            else
                L[i][j] = max(L[i-1][j],L[i][j-1]);
        }
    }
    return L[m][n];
}
like image 188
Zack Avatar answered Jun 22 '26 21:06

Zack