最长的共同子序列

Pro*_*mer 8 c# algorithm

我已经为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;

    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Hei*_*nzi 9

为什么你认为你的算法坏了?最长的公共子序列ACCTAGTATTGTTC,长度为14个字符:

string B = "AAACCGTGAGTTATTCGTTCTAGAA";
              ^^^ ^ ^^ ^^^^ ^^^^

string A = "CACCCCTAAGGTACCTTTGGTTC";
             ^^^  ^ ^^ ^^  ^^ ^ ^^^
Run Code Online (Sandbox Code Playgroud)

(我修改了你的算法以返回序列而不仅仅是长度.)

  • 我们在哪里可以找到修改后的算法? (4认同)
  • @Arjang:这是留给读者的练习.;-)如果您了解原始算法的工作原理,那么这种修改不应该太难. (2认同)
  • @Heinzi 你能展示返回序列的源代码吗? (2认同)