forked from int28h/JavaTasks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcs.java
More file actions
40 lines (33 loc) · 917 Bytes
/
lcs.java
File metadata and controls
40 lines (33 loc) · 917 Bytes
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
public class LCS {
private static String lcs(String s1, String s2) {
int l1 = s1.length();
int l2 = s2.length();
char[] str1 = s1.toCharArray();
char[] str2 = s2.toCharArray();
int[][] lengths = new int[l1][l2];
int greatestL = 0;
String result = "";
for(int i = 0; i < l1; i++) {
for(int j = 0; j < l2; j++) {
if(str1[i] == str2[j]) {
if(i == 0 || j == 0) {
lengths[i][j] = 1;
} else {
lengths[i][j] = lengths[i - 1][j - 1] + 1;
}
if(lengths[i][j] > greatestL) {
greatestL = lengths[i][j];
//System.out.println(" i = " + i + ", greatest = " + greatestL);
result = s1.substring(i - greatestL + 1, i + 1);
}
} else {
lengths[i][j] = 0;
}
}
}
return result;
}
public static void main(final String[] args) throws Exception {
System.out.println(lcs("thisisatest", "testing123testing"));
}
}