shortest common supersequence(DP, LCS based,cpp)

 shortest common supersequence.

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences.  If multiple answers exist, you may return any of them.


Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation: 
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.
////////////////////////////////////////////////////////////////////////////////////////////// 


 string shortestCommonSupersequence(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]);
}
}
}
}


string x;
int i=t1.size(); // a==t1;

int j=t2.size(); // b==t2;

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

}
while(i>0)
{
x.push_back(t1[i-1]);
i--;
}
while(j>0)
{
x.push_back(t2[j-1]);
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).