-
Notifications
You must be signed in to change notification settings - Fork 2
Longest Common Subsequence (LCS)
Rafiul Islam edited this page Nov 23, 2018
·
3 revisions
-
col[0] A
B
C
D
row[0] 0 0 0 0 0 B
0 C
0 -
for(int i=1; i<=len1; i++)
{
// iterate second string
for(int j=1; j<=len2; j++)
{
/*
whether current index of string1 and string2 item match each
other then set table value for this two index
previous diagonal index + 1;
otherwise set the maximum of corresponding row neighbor item
and corresponding column item.
*/
if(str1.at(i-1) == str2.at(j-1))
table[i][j] = table[i-1][j-1]+1;
else
table[i][j] = max(table[i-1][j],table[i][j-1]);
}
}
|
col[0] | A |
B |
C |
D |
---|---|---|---|---|---|
row[0] | 0 | 0 | 0 | 0 | 0 |
B |
0 | 0 | 1 | 1 | 1 |
C |
0 | 1 | 1 | 2 | 2 |
for(int i=len1,j=len2,index=table[len1][len2]; i!=0 && j!=0; )
{
if(str1.at(i-1) == str2.at(j-1))
{
// set the char in corresponding index
seq.at(index-1) = str1.at(i-1);
i--;
j--;
index--;
}
// check current value comes from which neighbor
else if(table[i][j-1] < table[i-1][j])
i--;
else
j--;
}