Given a string, find all ways to to break the given string in bracket form. Enclose each substring within a parenthesis.
Input : abc Output: (a)(b)(c) (a)(bc) (ab)(c) (abc) Input : abcd Output : (a)(b)(c)(d) (a)(b)(cd) (a)(bc)(d) (a)(bcd) (ab)(c)(d) (ab)(cd) (abc)(d) (abcd)
We strongly recommend you to minimize your browser and try this yourself first.
The idea is to use recursion. We maintain two parameters – index of the next character to be processed and the output string so far. We start from index of next character to be processed, append substring formed by unprocessed string to the output string and recurse on remaining string until we process the whole string. We use std::substr to form the output string. substr(pos, n) returns a substring of length n that starts at position pos of current string.
Below diagram shows recursion tree for input string “abc”. Each node on the diagram shows processed string (marked by green) and unprocessed string (marked by red).
Below is its implementation-
(a)(b)(c)(d) (a)(b)(cd) (a)(bc)(d) (a)(bcd) (ab)(c)(d) (ab)(cd) (abc)(d) (abcd)
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Return maximum occurring character in an input string
- Print all the duplicates in the input string
- Remove characters from the first string which are present in the second string
- Remove duplicates from a given string
- Print reverse of a string using recursion
- Write a program to print all permutations of a given string
- Divide a string in N equal parts
- Given a string, find its first non-repeating character
- Write a program to reverse an array or string
- Print list items containing all characters of a given word
- Reverse words in a given string
- Find the smallest window in a string containing all characters of another string
- Print all permutations with repetition of characters
- Print all interleavings of given two strings
- Lexicographic rank of a string
Improved By : shrikanth13