-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonSubsequence.java
More file actions
70 lines (59 loc) · 1.54 KB
/
LongestCommonSubsequence.java
File metadata and controls
70 lines (59 loc) · 1.54 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.*;
public class LongestCommonSubsequence {
int[][] lcsMat;
private void constructLCSMatrix(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
int i, j;
lcsMat = new int[len1 + 1][len2 + 1];
for (i = 1; i <= len1; i++) {
for (j = 1; j <= len2; j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
lcsMat[i][j] = lcsMat[i-1][j-1] + 1;
} else {
if (lcsMat[i-1][j] > lcsMat[i][j-1]) {
lcsMat[i][j] = lcsMat[i-1][j];
} else {
lcsMat[i][j] = lcsMat[i][j-1];
}
}
}
}
}
private String computeLCS(String str1, String str2) {
int i = str1.length();
int j = str2.length();
String lcs = "";
if (i == 0 || j == 0) {
return lcs;
}
constructLCSMatrix(str1, str2);
while (lcsMat[i][j] != 0) {
while(lcsMat[i-1][j] == lcsMat[i][j]) {
i--;
}
while(lcsMat[i][j-1] == lcsMat[i][j]) {
j--;
}
i--;
j--;
lcs = str1.charAt(i) + lcs;
}
return lcs;
}
public LongestCommonSubsequence (String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
while ((line = br.readLine()) != null) {
String[] params = line.split(";");
System.out.println(computeLCS(params[0], params[1]));
}
}
public static void main (String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Unsupported number of parameters passed. Exiting.");
System.exit(1);
}
LongestCommonSubsequence lcs = new LongestCommonSubsequence(args[0]);
}
}