File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed
Algorithms/Dynamic Programming Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
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<<" \n Enter the 1st string: " ;
51
+ cin>>arr1;
52
+
53
+ cout<<" \n Enter the 2nd string: " ;
54
+ cin>>arr2;
55
+
56
+ int s1 = strlen (arr1);
57
+ int s2 = strlen (arr2);
58
+
59
+ cout << " \n Length of the Longest Common Subsequence is: "
60
+ << longestCommonSubsequence ( arr1, arr2, s1, s2 )<<endl;
61
+
62
+ return 0 ;
63
+ }
You can’t perform that action at this time.
0 commit comments