Saturday, January 12, 2013

C++ program to find all the possible interleavings of two input strings


#include<iostream>
#include<string.h>
#include<map>
using namespace std;
map<string,bool> myMap;
void generateInterleaved(char A[100],char B[100],char out[200],int start1,int start2)
{
if(strlen(out)==strlen(A)+strlen(B))
{
if(myMap.find(out) == myMap.end())
{
myMap[out]=true;
}
return;
}
else
{
if(start1<strlen(A))
{
out[strlen(out)]=A[start1];
generateInterleaved(A,B,out,start1+1,start2);
out[strlen(out)-1]=0;
}
if(start2<strlen(B))
{
out[strlen(out)]=B[start2];
generateInterleaved(A,B,out,start1,start2+1);
out[strlen(out)-1]=0;
}
}
}
int main()
{
char A[100],B[100],C[100];
bool isInterleaved(char[],char[],char[]);
cin>>A>>B>>C;
bool result=isInterleaved(A,B,C);
if(result==true)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
char out[200]={0};
cout<<"The possible interleavings are:\n";
generateInterleaved(A,B,out,0,0);
for(map<string,bool>::iterator it = myMap.begin();it != myMap.end(); ++it)
{
cout<<it->first<<endl;
}
}
bool isInterleaved(char A[100],char B[100],char C[100])
{
int j=0,k=0;
for(int i=0;i<strlen(C);i++)
{
if(j<strlen(A) && C[i]==A[j])
{
j++;
}
else if(k<strlen(B) && C[i]==B[k])
{
k++;
}
}
if(j==strlen(A) && k==strlen(B))
{
return true;
}
else
{
return false;
}
}
Input:
ab
cd
Output:
ab
cd
abcd
YES
The possible interleavings are:
abcd
acbd
acdb
cabd
cadb
cdab

No comments:

Post a Comment