shortest common supersequence java code example
Example: shortest common supersequence
string scs_string(string x,string y,int n,int m) {
int dp[n+1][m+1];
for(int i=0;i<=n;i++) {
for(int j=0;j<=m;j++) {
if(i==0 || j==0) {
dp[i][j] = 0;
continue;
}
if(x[i-1]==y[j-1]) {
dp[i][j] = 1+dp[i-1][j-1];
}
else
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
string s;
int i=n;
int j=m;
while(i>0 && j>0) {
if(x[i-1]==y[j-1]) {
s.push_back(x[i-1]);
i--;
j--;
}
else {
if(dp[i-1][j]>dp[i][j-1]) {
s.push_back(x[i-1]);
cout<<x[i-1]<<" , "<<y[j-1]<<endl;
i--;
}
else {
s.push_back(y[j-1]);
cout<<x[i-1]<<" , "<<y[j-1]<<endl;
j--;
}
}
}
while(i>0) {
s.push_back(x[i-1]);
i--;
}
while(j>0) {
s.push_back(x[j-1]);
j--;
}
reverse(s.begin(),s.end());
return s;
}