I have written the below code for LCS. It works for many cases but breaks for the one below. I do not understand where my code is breaking. Please help. The code is in C#
namespace LongestCommonSubsequenceBF
{
class Program
{
static void Main(string[] args)
{
string B = "AAACCGTGAGTTATTCGTTCTAGAA";
string A = "CACCCCTAAGGTACCTTTGGTTC";
//find LCS in A,B starting from index 0 of each
int longestCommonSubsequence = LCS(A, B, 0, 0);
Console.WriteLine(longestCommonSubsequence);
Console.Read();
}
//Find the longest common subsequnce starting from index1 in A and index2 in B
//Pass A as shorter string
public static int LCS(String A, String B, int index1, int index2)
{
int max = 0;
if (index1 == A.Length)
{
//You have reached beyond A and thus no subsequence
return 0;
}
if (index2 == B.Length)
{ //you may reach end of 2nd string. LCS from that end is 0
return 0;
}
for (int i = index1; i < A.Length ; i++)
{
int exist = B.IndexOf(A[i],index2);
if (exist != -1)
{
// found = true;
int temp = 1 + LCS(A, B, i + 1, exist + 1);
if (max < temp)
{
max = temp;
}
}
}
return max;
}
}
}
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, '”acefg”, .. etc are subsequences of “abcdefg”.
The longest common subsequence problem is a classic computer science problem, the basis of data comparison programs such as the diff utility, and has applications in computational linguistics and bioinformatics.
The general algorithms which are followed to solve the Longest Common Subsequence (LCS) problems have both time complexity and space complexity of O(m * n).
Dynamic Programming This algorithm will print the longest common subsequence of X and Y.
Why do you think your algorithm is broken? The longest common subsequence is ACCTAGTATTGTTC
, which is 14 characters long:
string B = "AAACCGTGAGTTATTCGTTCTAGAA";
^^^ ^ ^^ ^^^^ ^^^^
string A = "CACCCCTAAGGTACCTTTGGTTC";
^^^ ^ ^^ ^^ ^^ ^ ^^^
(I modified your algorithm to return the sequence instead of just the length.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With