
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements