简体   繁体   中英

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.

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

Any help you would appreciated.

Tested Cases:

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

returns 4 but string sequence is incorrect.

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

returns 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]. Your example of wrong printout ("MAN" instead of "HMAN") matches this, as H is the first char.

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++.

Try switching to -1 as stopping condition, or pad your strings at the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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