This is a C++ Program that Solves Longest common subsequence using Dynamic Programming technique.
There are 2 strings str1 and str2. Find the length of the longest subsequence common to both str1 and str2.
This problem can be solved using dynamic programming. First we will calculate the length of longest common subsequence for a prefix of str1 and str2. Then, we will tabulate these values in a matrix and use these values to calculate the value of LCS for longer prefixes of str1 and str2.
Time complexity – O(len1*len2)
str1="abcda" str2="bdabac" LCS=3 given by the subsequence "abc"
str1="sbbksg" str2="bpkpsjg" LCS=4 given by the subsequence "bksg"
str1="classical" str2="musical" LCS=5 given by subsequence "sical"
Here is source code of the C++ Program to Solve Longest common subsequence. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
using namespace std;
int longestCommonSubsequece(string str1, string str2, int len1, int len2)
int i, j;
//create a matrix of order (len1+1)*(len2+1) to tabulate values
//LCS[i][j]=Length of longest common subsequence of str1[0....(i-1)] and str2[0...(j-1)]
LCS[i]=0; //empty str2
LCS[j]=0; //empty str1
//now, start filling the matrix row wise
//if current character of both strings match
//now, return the final value
cout<<"Enter first string ";
cout<<"Enter second string ";
int len1=str1.length(); //length of str1
int len2=str2.length(); //length of str2
cout<<"Length of longest common subsequence is "<<longestCommonSubsequece(str1,str2,len1,len2);
In the main function, we will take input for str1 and str2. We will pass these to the function longestCommonSubsequence as parameters. This function will calculate the result using bottom up DP and return the value which is displayed on the standard output.
Case-1: $ g++ lcs.cpp $ ./a.out Enter first string classical Enter second string musical Length of longest common subsequence is 5
Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.