Skip to content

Commit 38f77e7

Browse files
authored
Create LongestCommonSubsequence.java
1 parent 03259bd commit 38f77e7

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import java.io.*;
2+
3+
public class Main {
4+
public static void main(String[] args) {
5+
try {
6+
File file = new File(args[0]);
7+
BufferedReader in = new BufferedReader(new FileReader(file));
8+
String line;
9+
while ((line = in.readLine()) != null) {
10+
if (line.trim().equals(""))
11+
continue;
12+
String[] lineArray = line.split(";");
13+
if (lineArray.length > 0) {
14+
Process(lineArray);
15+
}
16+
}
17+
in.close();
18+
} catch (IOException e) {
19+
}
20+
}
21+
private static void Process(String[] lineArray) {
22+
String S1 = lineArray[0];
23+
String S2 = lineArray[1];
24+
String c = dyn(S1, S2);
25+
System.out.println(c);
26+
}
27+
28+
public static String dyn(String X, String Y) {
29+
int M = X.length();
30+
int N = Y.length();
31+
int[][] c = new int[M + 1][N + 1];
32+
String[][] b = new String[M + 1][N + 1];
33+
for (int i = 0; i <= M; i++) {
34+
c[i][0] = 0;
35+
b[i][0] = "";
36+
}
37+
for (int j = 0; j <= N; j++) {
38+
c[0][j] = 0;
39+
b[0][j] = "";
40+
}
41+
for (int i = 1; i <= M; i++)
42+
for (int j = 1; j <= N; j++) {
43+
if (X.charAt(i - 1) == Y.charAt(j - 1)) {
44+
c[i][j] = c[i - 1][j - 1] + 1;
45+
b[i][j] = b[i - 1][j - 1]
46+
+ String.valueOf(X.charAt(i - 1));
47+
} else {
48+
c[i][j] = Math.max(c[i - 1][j], c[i][j - 1]);
49+
if (c[i - 1][j] > c[i][j - 1])
50+
b[i][j] = b[i - 1][j];
51+
else
52+
b[i][j] = b[i][j - 1];
53+
}
54+
}
55+
return b[M][N];
56+
}
57+
58+
}
59+

0 commit comments

Comments
 (0)