[英]Longest Common Subsequence
我已經為LCS編寫了以下代碼。 它適用於許多情況,但對於下面的情況有所突破。 我不明白我的代碼在哪里破解。 請幫忙。 代碼在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;
}
}
}
為什么你認為你的算法壞了? 最長的常見子序列是ACCTAGTATTGTTC
,長度為14個字符:
string B = "AAACCGTGAGTTATTCGTTCTAGAA";
^^^ ^ ^^ ^^^^ ^^^^
string A = "CACCCCTAAGGTACCTTTGGTTC";
^^^ ^ ^^ ^^ ^^ ^ ^^^
(我修改了你的算法以返回序列而不僅僅是長度。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.