-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLongestCommonSubSeq.java
More file actions
51 lines (40 loc) · 1.29 KB
/
Copy pathLongestCommonSubSeq.java
File metadata and controls
51 lines (40 loc) · 1.29 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
public class LongestCommonSubSeq {
/**
* Author: Gaurav Shrivastava
*/
public static int LCS(char[] str1, char[] str2){
int ans[][] = new int [str1.length + 1][str2.length + 1];
for (int i = 0; i < str1.length + 1; i++) {
for (int j = 0; j < str2.length + 1; j++) {
if(i == 0|| j== 0){
ans[i][j] = 0;
}
//m and n are len of str1 and str2 respectively
//If last characters of both sequences match (or str1[m-1] == str2[n-1]) then
//L(str1[0..m-1], str2[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])
else if (str1[i-1] == str2[j-1]){
ans[i][j] = ans[i-1][j-1] + 1;
}
//If last characters of both sequences do not match (or str1[m-1] != str2[n-1]) then
//L(str1[0..m-1], str2[0..n-1]) = MAX ( L(str1[0..m-2], str2[0..n-1]), L(str1[0..m-1], str2[0..n-2])
else{
ans[i][j] = Math.max(ans[i-1][j], ans[i][j-1]);
}
}
}
/*printing purpose
* for (int i = 0; i < str1.length+1; i++) {
for (int j = 0; j < str2.length+1; j++) {
System.out.print(ans[i][j]);
}
System.out.println();
}*/
return ans[str1.length][str2.length];
}
//Driver code
public static void main(String[] args) {
String str1 = "AGGATAB";
String str2 = "GXTXAYB";
System.out.print(LCS(str1.toCharArray(), str2.toCharArray()));
}
}