Given an encoded string s, decode it by expanding the pattern k[substring], where the substring inside brackets is written k times. k is guaranteed to be a positive integer, and encodedString contains only lowercase english alphabets. Return the final decoded string.
Note: The test cases are generated so that the length of the output string will never exceed 105 .
Examples:
Input: s = "3[b2[ca]]"
Output: "bcacabcacabcaca"
Explanation:
Inner substring “2[ca]” breakdown into “caca”.
Now, new string becomes “3[bcaca]”
Similarly “3[bcaca]” becomes “bcacabcacabcaca” which is final result.Input: s = "3[ab]"
Output: "ababab"
Explanation: The substring "ab" is repeated 3 times giving "ababab".
Table of Content
Using Two Stacks - O(n) Time and O(n) Space
The idea is to use two stacks: one to store the repeat counts and another to store the characters. Whenever a closing bracket ] is encountered, extract the substring inside the matching [ and repeat it according to the stored count. Push the expanded substring back into the character stack. Finally, pop all characters from the stack to obtain the decoded string.
Working of Approach:
- Traverse the string character by character.
- If a digit is found, form the complete number and push it into the number stack.
- Push all letters and opening brackets [ into the character stack.
- When ] is encountered, pop characters until [ is found, repeat the extracted substring using the top count from the number stack, and push the expanded string back into the character stack.
- After processing the entire string, pop all characters from the stack to build the final decoded string.
Illustration:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
string decodedString(string &s) {
stack<int> numStack;
stack<char> charStack;
string temp = "";
string res = "";
for (int i = 0; i < s.length(); i++) {
int cnt = 0;
// If Digit, convert it into number and
// push it into integerstack.
if (s[i] >= '0' && s[i] <= '9') {
while (s[i] >= '0' && s[i] <= '9') {
cnt = cnt * 10 + s[i] - '0';
i++;
}
i--;
numStack.push(cnt);
}
// If closing bracket ']' is encountered
else if (s[i] == ']') {
temp = "";
cnt = numStack.top();
numStack.pop();
// pop element till opening bracket '[' is not found in the
// character stack.
while (charStack.top() != '[') {
temp = charStack.top() + temp;
charStack.pop();
}
charStack.pop();
// Repeating the popped string 'temp' count number of times.
for (int j