A string that may contain multiple consecutive instances of the same value is encoded to only store that value and its count. Given such an encoded sequence, decode it.

A string inside the parenthesis will be repeated exactly as many times as the number preceding it. For example,

Input: str = 2(a)1(b)c4(de)f
Output: aabcdedededef
 
Input: str = 2(a2(b)c)
Output: abbcabbc
 
Input: str = a1(bc)4(c2(d)e)f10(h)
Output: abccddecddecddecddefhhhhhhhhhh

You may presume that the number is non-negative and is exactly followed by a string within the parenthesis. Additionally, the input text has matching parenthesis and is free of whitespace.

1. Using Recursion

We can use recursion to solve this problem. The idea is to traverse the string, starting from the last processed index in the caller function. If we encounter a starting bracket '(', recursively decode the substring starting with '(' and ending with the matching ')'. After each recursive call, the decoded substring is appended to the result as many times as the number preceding '('. We follow the process recursively until the end of the string is reached.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

abccddecddecddecddefhhhhhhhhhh

Java


Download  Run Code

Output:

abccddecddecddecddefhhhhhhhhhh

Python


Download  Run Code

Output:

abccddecddecddecddefhhhhhhhhhh

The time complexity of the above solution is O(n) and requires O(n) extra space for the call stack, where n is the length of the string.

2. Using Iteration

We can convert the above recursive procedure into an iterative one using an explicit stack. Following is a simple stack-based iterative algorithm to construct a string from an encoded sequence:

C++


Download  Run Code

Output:

abccddecddecddecddefhhhhhhhhhh

Java


Download  Run Code

Output:

abccddecddecddecddefhhhhhhhhhh

Python


Download  Run Code

Output:

abccddecddecddecddefhhhhhhhhhh

The time complexity of the above solution is O(n) and requires O(n) extra space for the stack data structure, where n is the length of the string.