Skip to content

Commit 0b38012

Browse files
authored
Longest Common Subsequence in C++.
1 parent 15d054f commit 0b38012

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

LCS.cpp

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include<bits/stdc++.h>
2+
#include<string.h>
3+
using namespace std;
4+
//This function will return longest common subsequence of two given string;
5+
int LCS(char str1[], char str2[], int n, int m)
6+
{
7+
vector<char>vec;
8+
int L[n+1][m+1]; //initialize a 2D array;
9+
int i,j;
10+
for(i=0;i<=n;i++)
11+
{
12+
for(j=0;j<=m;j++)
13+
{
14+
if(i==0 || j==0)
15+
L[i][j]=0;
16+
else if(str1[i-1]==str2[j-1]) //if 'i'th character of 1st string equal to 'j'th character of
17+
{ //2nd string then push that character to the vector and go for
18+
L[i][j]=1+L[i-1][j-1]; //next character of both string;
19+
vec.push_back(str1[i-1]);
20+
}
21+
else //else return max of 'i-1' characters of 1st string and j characters
22+
L[i][j]=max(L[i-1][j],L[i][j-1]); //and 'i' characters of 1st string and 'j-1' characters of
23+
} //2nd sgtring;
24+
}
25+
int c=L[n][m];
26+
cout << "\nLargest Common Subsequence is: ";
27+
for(int i=vec.size()-c;i<vec.size();i++) //print longest common subsequence;
28+
cout << vec[i];
29+
cout << endl;
30+
return L[n][m]; //return length of longest common subsequence;
31+
}
32+
int main()
33+
{
34+
char str1[100],str2[100];
35+
cout << "Enter the two string: " << endl;
36+
cin>>str1>>str2; //enter two string;
37+
int n=strlen(str1); //length of first string;
38+
int m=strlen(str2); //length of second string;
39+
cout << "Length of Largest Common Subsequence: " << LCS(str1, str2, n, m); //print LCS of two string;
40+
return 0;
41+
}

0 commit comments

Comments
 (0)