-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Common Subsequence
55 lines (54 loc) · 1.44 KB
/
Longest Common Subsequence
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
public class LongestCommonSubsequence {
static void sub(int[][] m, char s1[],char s2[],int size)
{
int index = size;
int i=5,j=7;
char[] fin = new char[size+1];
while(i>0 && j>0)
{
if(s1[i] == s2[j] && index>=0)
{
fin[index-1] = s1[i];
i--; j--; index--;
}
else if(m[i-1][j]>m[i][j-1])
{ i--; }
else{ j--; }
}
System.out.print("Longest common subsequence are : ");
for(int k=0;k<size;k++)
{
System.out.print(fin[i]+" ");
}
}
public static void main(String arg[])
{
char s1[] = {'0','s','t','o','n','e'};
char s2[] = {'0','l','o','n','g','e','s','t'};
int m[][] = new int[6][8];
for(int i=0;i<6;i++)
{
for(int j=0;j<8;j++)
{
if(i==0 || j==0)
{
m[i][j]=0;
}
else
{
if(s1[i]==s2[i])
{
m[i][j] = m[i-1][j-1]+1;
}
else
{
m[i][j] = Math.max(m[i][j-1],m[i-1][j]);
}
}
}
}
int s = m[5][7];
System.out.println("size of longest common subsequence is : "+s);
sub(m,s1,s2,s);
}
}