Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Stack & Queue

Decode a Nested String

Medium · Stack & Queue · Asked at Google, Amazon, Microsoft, Bloomberg

Decode a string written with the rule k[text], meaning text repeated k times. Brackets can be nested, e.g. 3[a2[c]] → accaccacc. Letters outside brackets stay as they are. Print the decoded string.

Input

A single line with the encoded string (lowercase letters, digits and brackets; it is always well-formed).

Output

The decoded string.

Constraints

Use two stacks: one for repeat counts and one for the text built before each [. On ], pop both and set current = previous + current repeated k times. Digits can form numbers with several digits.

Example 1

Input

3[a]2[bc]

Output

aaabcbc

Example 2

Input

3[a2[c]]

Output

accaccacc

Example 3

Input

2[abc]3[cd]ef

Output

abcabccdcdcdef

Hints

  1. The innermost brackets must be expanded first — that is what a stack gives you.
  2. At each "[", save the text built so far and the repeat count, then start fresh.
  3. At "]", the finished inner text is repeated and appended to the saved text.

Approach

Scan once with the current text cur and the number being read k. Digits extend k (counts can have several digits). "[" pushes (cur, k) and resets both. "]" pops (prev, times) and sets cur = prev + cur repeated times. Letters are appended to cur. At the end cur is the decoded string.

Complexity: O(length of the output) time and space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    vector<string> prev;
    vector<int> counts;
    string cur;
    int k = 0;
    for (char c : s) {
        if (isdigit(c)) k = k * 10 + (c - '0');
        else if (c == '[') {
            counts.push_back(k);
            prev.push_back(cur);
            k = 0;
            cur.clear();
        } else if (c == ']') {
            string rep;
            for (int i = 0; i < counts.back(); i++) rep += cur;
            cur = prev.back() + rep;
            prev.pop_back();
            counts.pop_back();
        } else cur += c;
    }
    cout << cur << "\n";
    return 0;
}

Python solution

s = input().strip()
stack = []
cur, k = "", 0
for c in s:
    if c.isdigit():
        k = k * 10 + int(c)
    elif c == "[":
        stack.append((cur, k))
        cur, k = "", 0
    elif c == "]":
        prev, times = stack.pop()
        cur = prev + cur * times
    else:
        cur += c
print(cur)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
        ArrayDeque<StringBuilder> prev = new ArrayDeque<>();
        ArrayDeque<Integer> counts = new ArrayDeque<>();
        StringBuilder cur = new StringBuilder();
        int k = 0;
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) k = k * 10 + (c - '0');
            else if (c == '[') {
                counts.push(k);
                prev.push(cur);
                k = 0;
                cur = new StringBuilder();
            } else if (c == ']') {
                StringBuilder outer = prev.pop();
                int times = counts.pop();
                for (int i = 0; i < times; i++) outer.append(cur);
                cur = outer;
            } else cur.append(c);
        }
        System.out.println(cur);
    }
}

Solve Decode a Nested String online · All practice problems