-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLongestCommonSubsequence.cpp
68 lines (66 loc) · 1.51 KB
/
LongestCommonSubsequence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<bits/stdc++.h>
#include<string>
using namespace std;
int max(int x,int y)
{
return (x>y)?x:y;
}
int LongestCommonSubsequence(string string1,string string2,int m,int n)
{
int lcs[m+1][n+1];
for(int i=0;i<=m;i++)
{
for(int j=0;j<=n;j++)
{
if(i==0||j==0)
{
lcs[i][j]=0;
}
else if(string1.at(i-1)==string2.at(j-1))
{
lcs[i][j]=lcs[i-1][j-1]+1;
}
else
{
lcs[i][j]=max(lcs[i-1][j],lcs[i][j-1]);
}
}
}
int length= lcs[m][n];
char sequence[length+1];
int i=m;
int j=n;
while(i>0 && j>0)
{
if (string1.at(i - 1) == string2.at(j - 1))
{
sequence[length-1]=string1.at(i-1);
i--;
j--;
length--;
}
else if(lcs[i-1][j]>lcs[i][j-1])
{
i--;
}
else
{
j--;
}
}
cout<<"The Longest Common Subsequence of entered strings:"<<sequence<<"\n";
return lcs[m][n];
}
int main()
{
string string1;
string string2;
cout<<"Enter 1st String:\n";
cin>>string1;
cout<<"Enter 2nd String:\n";
cin>>string2;
int m=string1.size();
int n=string2.size();
int length=LongestCommonSubsequence(string1,string2,m,n);
cout<<"So Length of Longest Common Subsequence:"<<length;
}