forked from TheAlgorithms/Java
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonSubsequence.java
More file actions
Latest commit
66 lines (57 loc) · 1.73 KB
/
Copy pathLongestCommonSubsequence.java
File metadata and controls
66 lines (57 loc) · 1.73 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
classLongestCommonSubsequence {
publicstaticStringgetLCS(Stringstr1, Stringstr2) {
//At least one string is null
if(str1 == null || str2 == null)
returnnull;
//At least one string is empty
if(str1.length() == 0 || str2.length() == 0)
return"";
String[] arr1 = str1.split("");
String[] arr2 = str2.split("");
//lcsMatrix[i][j] = LCS of first i elements of arr1 and first j characters of arr2
int[][] lcsMatrix = newint[arr1.length + 1][arr2.length + 1];
for(inti = 0; i < arr1.length + 1; i++)
lcsMatrix[i][0] = 0;
for(intj = 1; j < arr2.length + 1; j++)
lcsMatrix[0][j] = 0;
for(inti = 1; i < arr1.length + 1; i++) {
for(intj = 1; j < arr2.length + 1; j++) {
if(arr1[i-1].equals(arr2[j-1])) {
lcsMatrix[i][j] = lcsMatrix[i-1][j-1] + 1;
} else {
lcsMatrix[i][j] = lcsMatrix[i-1][j] > lcsMatrix[i][j-1] ? lcsMatrix[i-1][j] : lcsMatrix[i][j-1];
}
}
}
returnlcsString(str1, str2, lcsMatrix);
}
publicstaticStringlcsString (Stringstr1, Stringstr2, int[][] lcsMatrix) {
StringBuilderlcs = newStringBuilder();
inti = str1.length(),
j = str2.length();
while(i > 0 && j > 0) {
if(str1.charAt(i-1) == str2.charAt(j-1)) {
lcs.append(str1.charAt(i-1));
i--;
j--;
} elseif(lcsMatrix[i-1][j] > lcsMatrix[i][j-1]) {
i--;
} else {
j--;
}
}
returnlcs.reverse().toString();
}
publicstaticvoidmain(String[] args) {
Stringstr1 = "DSGSHSRGSRHTRD";
Stringstr2 = "DATRGAGTSHS";
Stringlcs = getLCS(str1, str2);
//Print LCS
if(lcs != null) {
System.out.println("String 1: " + str1);
System.out.println("String 2: " + str2);
System.out.println("LCS: " + lcs);
System.out.println("LCS length: " + lcs.length());
}
}
}