forked from AllAlgorithms/java
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonSubsequence.java
More file actions
Latest commit
43 lines (39 loc) · 1.08 KB
/
Copy pathLongestCommonSubsequence.java
File metadata and controls
43 lines (39 loc) · 1.08 KB
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
// Finding Longest Common Subsequence of Two Strings Using Dynamic Programming
importjava.util.Scanner;
publicclassLongestCommonSubsequence {
intlcs(char[] X, char[] Y, intm, intn) {
intDP[][] = newint[m + 1][n + 1];
// Bottom-Up Approach for dp
for (inti = 0; i <= m; i++) {
for (intj = 0; j <= n; j++) {
if (i == 0 || j == 0)
DP[i][j] = 0;
elseif (X[i - 1] == Y[j - 1])
DP[i][j] = DP[i - 1][j - 1] + 1;
else
DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]);
}
}
returnDP[m][n];
}
intmax(inta, intb) {
if (a > b)
returna;
else
returnb;
}
publicstaticvoidmain(String[] args) {
LongestCommonSubsequenceobj = newLongestCommonSubsequence();
Strings1 = "", s2 = "";
Scannerscan = newScanner(System.in);
System.out.println("Enter 1st String");
s1 = scan.next();
System.out.println("Enter 2nd String");
s2 = scan.next();
char[] X = s1.toCharArray();
char[] Y = s2.toCharArray();
intm = X.length;
intn = Y.length;
System.out.println("Length of Longest Common Subsequence is: " + obj.lcs(X, Y, m, n));
}
}