
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 Ways to Break a String in Bracket Form in C++
In this problem, we are given a string and we have to break it into substrings and print them enclosing brackets.
Let’s take a few examples to understand the problem better,
Input : wxyz Output : (w) (x) (y) (z) (w) (x) (yz) (w) (xy) (z) (w) (xyz) (wx) (y) (z) (wx) (yz) (wxy) (z) (wxyz)
Explanation − We will break the string into all possible substrings. And enclose each substring with brackets.
Now, since we have understood the problem, let’s create a solution to the problem.
Here, we will use recursion to solve the problem. We will use two parameters, one will be the next character of the string and the other is the output string. The unprocessed substring will slowly be processed at each iteration. And the subsets are created.
Example
Program to solve the problem −
#include <iostream> using namespace std; void substring(string str, int index, string out){ if (index == str.length()) cout << out << endl; for (int i = index; i < str.length(); i++) substring(str, i + 1, out + "(" + str.substr(index, i+1-index) + ")" ); } int main(){ string str = "wxyz"; cout<<”The substring are :”<<endl; substring(str, 0, ""); return 0; }
Output
The substring are : (w)(x)(y)(z) (w)(x)(yz) (w)(xy)(z) (w)(xyz) (wx)(y)(z) (wx)(yz) (wxy)(z) (wxyz)
Advertisements