简体   繁体   English

最长公共子序列错误打印

[英]Longest Common Subsequence incorrect printing

I have been trying to implement the Longest Common Subsequence for a few hours now. 我已经尝试实施几个小时的最长公共子序列。 I have checked that LCSLength function returns correct length, but it is not printing the sequence correctly. 我已经检查过LCSLength函数返回正确的长度,但是它没有正确打印序列。

int max(int a , int b)
{
    if(a>b) 
        return a;
    else 
        return b;
}
/* The printing function that is not functioning Properly */
string backtrack(vector< vector<int> > C, string X,string Y,int i,int j)
{
    if( i==0  || j==0)
        return "";
    else if( X[i] == Y[j])
        return backtrack(C,X,Y,i-1,j-1) + X[i];
    else
        if( C[i][j-1] >= C[i-1][j] )
            return backtrack(C,X,Y,i,j-1);
        else
            return backtrack(C,X,Y,i-1,j);

}



   /* It correctly returns the subsequence length. */
   int LCSLength(string s1,string s2)
   {   
        vector< vector <int> >  C (s1.size()+1 , vector<int> (s2.size() +1 ) );
        int i,j;
        int m = s1.size();
        int n = s2.size();
        for(i =0; i<=m; i++){
        for( j =0; j<=n; j++){
            if( i==0 || j==0)
                C[i][j] = 0;
            else if( s1[i-1] == s2[j-1] )
                C[i][j] = C[i-1][j-1] +1;
            else
                C[i][j] = max(C[i][j-1],C[i-1][j]);
        }
    }




    cout << backtrack(C,s1,s2,m,n);


    return C[m][n];
}

I am following pseudocode given here: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem 我正在遵循此处给出的伪代码: http : //en.wikipedia.org/wiki/Longest_common_subsequence_problem

Any help you would appreciated. 任何帮助,您将不胜感激。

Tested Cases: 测试案例:

 cout << LCSLength("HUMAN", "CHIMPANZEE") << endl;

returns 4 but string sequence is incorrect. 返回4,但字符串顺序不正确。

  cout << LCSLength("AAACCGTGAGTTATTCGTTCTAGAA","CACCCCTAAGGTACCTTTGGTTC") << endl;

returns 14 返回14

Thanks. 谢谢。

I'm guessing that since your stopping condition is : 我猜是因为您的停车条件是:

if( i==0  || j==0)
     return "";

You can never reach the character at X[0] or Y[0]. 您永远无法到达X [0]或Y [0]处的字符。 Your example of wrong printout ("MAN" instead of "HMAN") matches this, as H is the first char. 您的错误打印输出示例(“ MAN”而不是“ HMAN”)与此匹配,因为H是第一个字符。

Note that the wiki value you link is defining the strings as X[1..m] and Y[1..n] , which is probably not the intuitive way to do this in c++. 请注意,您链接的Wiki值将字符串定义为X[1..m] and Y[1..n] ,这可能不是在c ++中实现此目的的直观方法。

Try switching to -1 as stopping condition, or pad your strings at the beginning. 尝试切换到-1作为停止条件,或在开始时填充琴弦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM