C Program to Print all Interleaving of two Strings:Given two strings s1 and s2, write a function that will print all the interleavings of the given two strings. Here interleaving string is a string that has the same order that of individual strings.
C Program to Print all Interleaving of two Strings
#include <bits/stdc++.h>
using namespace std;
void printIlStrings(char *s1, char *s2, char *res, int m,
int n, int i)
{
if (m==0 && n==0)
{
cout<<res<<endl;
}
if (m != 0)
{
res[i] = s1[0];
printIlStrings(s1 + 1, s2, res, m-1, n, i+1);
}
if (n != 0)
{
res[i] = s2[0];
printIlStrings(s1, s2+1, res, m, n-1, i+1);
}
}
void printIls (char *s1, char *s2, int m, int n)
{
char *res = new char[m+n+1];
res[m+n] = '\0';
printIlStrings(s1, s2, res, m, n, 0);
free(res);
}
int main()
{
char s1[] = "AB";
char s2[] = "CD";
printIls (s1, s2, strlen(s1), strlen(s2));
return 0;
}
Output of Program
ABCD
ACBD
ACDB
CABD
CADB
CDAB