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.
Fixed my errors using some google searches. Indexing was my problem. Here is the correct code: