Skip to content

Commit 3a2afb2

Browse files
authored
Merge pull request manishbisht#55 from Rajdeep-G/master
Added Least Common Subsequence using Dp
2 parents 47dc99e + 8a3ae04 commit 3a2afb2

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
//Length of Longest Common Subsequence problem using Dynamic Programming
2+
3+
4+
#include<iostream>
5+
#include<string.h>
6+
using namespace std;
7+
8+
/* Function to get max of 2 integers */
9+
int max(int a, int b)
10+
{
11+
return (a > b)? a : b;
12+
}
13+
14+
15+
int longestCommonSubsequence( char *arr1, char *arr2, int m, int n )
16+
{
17+
int LCS[m + 1][n + 1];
18+
int i, j;
19+
20+
/* In the following steps LCS[i][j]
21+
contains length of Longest common subsequence of arr1[0..i-1]
22+
and arr2[0..j-1]. It uses a Dynamic programming approach */
23+
for (i = 0; i <= m; i++)
24+
{
25+
for (j = 0; j <= n; j++)
26+
{
27+
if (i == 0 || j == 0)
28+
LCS[i][j] = 0;
29+
30+
else if (arr1[i - 1] == arr2[j - 1])
31+
LCS[i][j] = LCS[i - 1][j - 1] + 1;
32+
33+
else
34+
LCS[i][j] = max(LCS[i - 1][j], LCS[i][j - 1]);
35+
}
36+
}
37+
38+
//Returns the longest common subsequence
39+
return LCS[m][n];
40+
}
41+
42+
43+
44+
//Main Function
45+
int main()
46+
{
47+
char arr1[100];
48+
char arr2[100];
49+
50+
cout<<"\nEnter the 1st string: ";
51+
cin>>arr1;
52+
53+
cout<<"\nEnter the 2nd string: ";
54+
cin>>arr2;
55+
56+
int s1 = strlen(arr1);
57+
int s2 = strlen(arr2);
58+
59+
cout << "\nLength of the Longest Common Subsequence is: "
60+
<< longestCommonSubsequence( arr1, arr2, s1, s2 )<<endl;
61+
62+
return 0;
63+
}

0 commit comments

Comments
 (0)