-
Notifications
You must be signed in to change notification settings - Fork 1
/
printLCS.java
75 lines (65 loc) · 1.63 KB
/
printLCS.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
68
69
70
71
72
73
74
75
// Print the Common SubSequance between two String.
public class PrintLCS{
public static void main(String []args){
String a = "aeiou";
String b = "asdertiop";
int lena = a.length();
int lenb = b.length();
int[][] arr = new int[lena + 1][lenb + 1];
int i ,j;
for (i =0;i<=lena;i++)
{
for(j =0;j<=lenb;j++)
{
if(i==0 || j == 0)
{
arr[i][j] = 0;
}
}
}
for(i = 1; i<=lena;i++)
{
for (j = 1; j<=lenb; j++)
{
if(a.charAt(i-1) == b.charAt(j-1))
{
arr[i][j] = 1 + arr[i-1][j-1];
}
else
{
arr[i][j] = Math.max(arr[i-1][j] , arr[i][j-1]);
}
}
}
i = lena;
j = lenb;
String str = "";
char k ;
while(i>0 && j>0 )
{
if(a.charAt(i-1) == b.charAt(j-1))
{
k = a.charAt(i-1);
str = str + k ;
i--;
j--;
}
else
{
if(arr[i-1][j] > arr[i][j-1])
{
i--;
}
else
j--;
}
}
String n = "";
j = str.length();
for(i = j ; i>0; i--)
{
n = n + str.charAt(i-1);
}
System.out.println(n);
}
}