forked from keshavsingh4522/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplcs.java
67 lines (47 loc) · 1.88 KB
/
implcs.java
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
public class Imp_lcs { //-------------------------------------1
public static void main (String[] args) {
String X = "AGGTAB"; //--------------------------------------2
String Y = "GXTXAYB"; //--------------------------------------2
int m = X.length(); //--------------------------------------3
int n = Y.length(); //--------------------------------------3
lcs_method(X, Y, m, n);
}
static void lcs_method (String X, String Y, int m, int n) { //-------4
int [][] arr = new int [m+1] [n+1]; //------------------------------5.a
for (int i = 0; i<=m; i++) { //---------------------------- ---5.b
for (int j = 0; j<=n; j++) { //--------------------------------5.b
if (i==0 || j==0){ //--------------------------------5.c.i
arr [i][j] = 0;
}
else if (X.charAt(i-1) == Y.charAt(j-1)) { //---------------5.c.ii
arr[i][j] = arr[i-1][j-1] + 1;
}
else {
arr [i][j] = Math.max(arr[i-1][j], arr[i][j-1]); //-------5.c.iii
}
}
}
int index = arr[m][n]; //--------------------------------5.d
int print = index;
char[] LCS = new char[index+1]; //--------------------------------5.e
LCS[index] = '\u0000'; // to set the terminating default value for character array
int i = m;
int j = n;
while (i>0 && j > 0){
if (X.charAt(i-1) == Y.charAt(j-1)){ //---------------------5.f.i
LCS[index-1] = X.charAt(i-1);
i--;
j--;
index--;
}
else if (arr[i-1][j] > arr[i][j-1]) //---------------------+5.d
i--;
else
j--;
}
System.out.print( "\n\nLCS of the sequence " +X+ " and sequence " +Y+ " is : ");
for (int k=0; k < print; k++) //---------------------+5.g
System.out.print( LCS[k]);
System.out.print( "\n\n" );
}
}