首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >最长公共子序列

最长公共子序列
EN

Stack Overflow用户
提问于 2011-01-05 02:27:28
回答 1查看 10.4K关注 0票数 8

我已经为LCS编写了以下代码。它在许多情况下都有效,但在下面的情况下会中断。我不知道我的代码在哪里崩溃了。请帮帮忙。代码在C#中

代码语言:javascript
复制
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;

    }
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-01-05 02:46:12

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

代码语言:javascript
复制
string B = "AAACCGTGAGTTATTCGTTCTAGAA";
              ^^^ ^ ^^ ^^^^ ^^^^

string A = "CACCCCTAAGGTACCTTTGGTTC";
             ^^^  ^ ^^ ^^  ^^ ^ ^^^

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

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4597010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档