

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print all interleavings of given two strings in C++
In this problem, we are given two string str1 and str2 and we have to print all interleaving strings from both the string.
Interleaving string created using two given strings such that the order of characters of each string.
Let’s take an example to understand the problem −
Input: str1 = “XY” str2= “NS” Output: XYNS, XNYS, XNSY, NXYS, NXSY, NSXY
To solve this problem, we will take all the characters in the strings. Length of str1 = m and length of str2 = n so we will create all interleaved strings from these strings.
For printing all interleaving strings, we will fix characters of strings and recursively call for all combinations of the string.
Example
Implementation of our logic −
#include <iostream> #include <string.h> using namespace std; void printStrings (char *str1, char *str2, char *iStr, int m, int n, int i) { if (m == 0 && n == 0) cout<<iStr<<endl ; if (m != 0) { iStr[i] = str1[0]; printStrings(str1 + 1, str2, iStr, m - 1, n, i + 1); } if (n != 0) { iStr[i] = str2[0]; printStrings(str1, str2 + 1, iStr, m, n - 1, i + 1); } } void generateInterleavingString(char *str1, char *str2, int m, int n) { char *iStr= new char[((m + n + 1)*sizeof(char))]; iStr[m + n] ='\0'; printStrings(str1, str2, iStr, m, n, 0); } int main() { char str1[] = "XY"; char str2[] = "NS"; cout<<"All interleaving string are :\n"; generateInterleavingString(str1, str2, strlen(str1), strlen(str2)); return 0; }
Output
All interleaving string is − XYNS XNYS XNSY NXYS NXSY NSXY
- Related Questions & Answers
- Print all pairs of anagrams in a given array of strings in C++
- Print all integers that are sum of powers of two given numbers in C++
- Print all permutations of a given string
- Print all sequences of given length in C++
- Print all nodes between two given levels in Binary Tree in C++
- Print common characters of two Strings in alphabetical order in C++
- Python Program to print all distinct uncommon digits present in two given numbers
- Print all subsets of given size of a set in C++
- Python code to print common characters of two Strings in alphabetical order
- Java code to print common characters of two Strings in alphabetical order
- Print all triplets with given sum in C++
- Print all pairs with given sum in C++
- Python - Find all the strings that are substrings to the given list of strings
- Print all distinct circular strings of length M in lexicographical order in C++
- Python Program to print all permutations of a given string
Advertisements