Skip to content

Commit 7e2499e

Browse files
Merge pull request #630 from Ankit-555/master
Added LCS in Java
2 parents 63d31ed + 3ca19bd commit 7e2499e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

LongestCommonSubsequence/LCS.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
public class LongestCommonSubsequence {
2+
3+
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
4+
int lcs(char[] X, char[] Y, int m, int n)
5+
{
6+
int L[][] = new int[m + 1][n + 1];
7+
8+
/* Following steps build L[m+1][n+1] in bottom up fashion. Note
9+
that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
10+
for (int i = 0; i <= m; i++) {
11+
for (int j = 0; j <= n; j++) {
12+
if (i == 0 || j == 0)
13+
L[i][j] = 0;
14+
else if (X[i - 1] == Y[j - 1])
15+
L[i][j] = L[i - 1][j - 1] + 1;
16+
else
17+
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
18+
}
19+
}
20+
return L[m][n];
21+
}
22+
23+
/* Utility function to get max of 2 integers */
24+
int max(int a, int b)
25+
{
26+
return (a > b) ? a : b;
27+
}
28+

0 commit comments

Comments
 (0)