Skip to content

Commit 89efb8c

Browse files
Merge pull request #571 from balasbk/master
longest comman subsequences
2 parents 81460c5 + d5a33c0 commit 89efb8c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

C++/LONGEST COMMON SUBSEQUENCE.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <bits/stdc++.h>
2+
3+
int max(int a, int b);
4+
5+
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
6+
int lcs(char* X, char* Y, int m, int n)
7+
{
8+
int L[m + 1][n + 1];
9+
int i, j;
10+
11+
/* Following steps build L[m+1][n+1] in bottom up fashion. Note
12+
that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
13+
for (i = 0; i <= m; i++) {
14+
for (j = 0; j <= n; j++) {
15+
if (i == 0 || j == 0)
16+
L[i][j] = 0;
17+
18+
else if (X[i - 1] == Y[j - 1])
19+
L[i][j] = L[i - 1][j - 1] + 1;
20+
21+
else
22+
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
23+
}
24+
}
25+
26+
/* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */
27+
return L[m][n];
28+
}
29+
30+
/* Utility function to get max of 2 integers */
31+
int max(int a, int b)
32+
{
33+
return (a > b) ? a : b;
34+
}
35+
36+
/* Driver program to test above function */
37+
int main()
38+
{
39+
char X[] = "AGGTAB";
40+
char Y[] = "GXTXAYB";
41+
42+
int m = strlen(X);
43+
int n = strlen(Y);
44+
45+
printf("Length of LCS is %d\n", lcs(X, Y, m, n));
46+
47+
return 0;
48+
}

0 commit comments

Comments
 (0)