Longest Common Subsequence in cpp - dp problem

 Given two strings text1 and text2, return the length  of their longest common subsequence (leetcode,c++).

 

Example 1:

Input: text1 = "abcde", text2 = "ace" 
Output: 3  
Explanation: The longest common subsequence is "ace" and its length is 3. 
//////////////////////////////////////////////////////////////////////////////////////// 

 

 int longestCommonSubsequence(string t1, string t2) {
        
        int t[t1.size()+1][t2.size()+1];
        for(int i=0;i<t1.size()+1;i++)
        {
            for(int j=0;j<t2.size()+1;j++)
            {
                if(i==0 || j==0)
                    t[i][j]=0;
                else
                {
                    if(t1[i-1]==t2[j-1])
                        t[i][j]=1+t[i-1][j-1];
                    else
                    {
                        t[i][j]=max(t[i-1][j],t[i][j-1]);
                    }
                }
            }
        }
        return t[t1.size()][t2.size()];
    }

=================================================

 

TO PRINT THE LONGEST COMMON SUBSEQUENCE

  vector<int>x;
    int i=a.size(); // a==t1;
 
    int j=b.size(); // b==t2;

    while(i>0 && j>0)
    {
        if(a[i-1]==b[j-1])
            {
                x.push_back(a[i-1]);
                i--;
                j--;
            }
        else
        {
            if(t[i-1][j]>t[i][j-1])
                i--;
            else
                j--;
        }

    }
    reverse(x.begin(),x.end());
    return x;


 

Comments

Popular posts from this blog

Amazing Subarrays(cpp,interviewbit)

Symmetric Tree(leetcode,cpp):

sum of left leaves in a tree(leetcode).