forked from IDeserve/learn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestCommonSubsequence.java
104 lines (88 loc) · 2.2 KB
/
LongestCommonSubsequence.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package questions.virendra;
import java.util.ArrayList;
import java.util.List;
public class LongestCommonSubsequence {
public static void commonSubsequence(String S1, String S2)
{
int s1_len = S1.length();
int s2_len = S2.length();
final int pick_s1_or_s2 = 0;
final int pick_s1 = 1;
final int pick_s2 = 2;
int match[][] = new int[s1_len][s2_len];
int pointer[][] = new int[s1_len][s2_len];
for(int i=0; i<s1_len; i++)
{
for(int j=0; j<s2_len; j++)
{
if(S1.charAt(i) == S2.charAt(j)) //Characters match
{
if((i==0) || (j==0)) //first row or first column
{
match[i][j] = 1; //initialize
}
else
{
match[i][j] = match[i-1][j-1] + 1;
}
pointer[i][j] = pick_s1_or_s2;
}
else //Characters mismatch
{
if((i > 0 ) && (j > 0)) //neither the first row nor first column
{
//Refer in ppt :- LCS(ACBE,ADC) = max(LCS(ACB,ADC), LCS(ACBE,AD))
//Thumb rule:- mismatch take max. if not in first row or column.
if(match[i-1][j] >= match[i][j-1])
{
match[i][j] = match[i-1][j];
pointer[i][j] = pick_s2; //ditch s1's character
}
else
{
match[i][j] = match[i][j-1];
pointer[i][j] = pick_s1;//ditch s2's character.
}
}
else if ((i==0) && ( j > 0)) //first row
{
match[i][j] = match[i][j-1];
pointer[i][j] = pick_s1;
}
else if((j==0) && (i>0)) //first column
{
match[i][j] = match[i-1][j];
pointer[i][j] = pick_s2;
}
}
}
}
//Printing the LCS.
int i = s1_len - 1;
int j = s2_len - 1;
StringBuffer result = new StringBuffer();
while(i>=0 && j>=0)
{
switch(pointer[i][j])
{
//go diagonal and collect the matched character
case pick_s1_or_s2:
result.append(S1.charAt(i));
i--;
j--;
break;
case pick_s1://go left
j--;
break;
case pick_s2://go up
i--;
break;
}
}
System.out.println(result.reverse());
}
public static void main(String args[])
{
commonSubsequence("ACBEA", "ADCA");
}
}