#394 Decode String

Medium

字符串解码

Problem

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly \(k\) times. Note that \(k\) is guaranteed to be a positive integer.

You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, \(k\). For example, there will not be input like 3a or 2[4].

The test cases are generated so that the length of the output will never exceed \(10^5\).

Example 1:

Input: s = "3[a]2[bc]"

Output: "aaabcbc"

Example 2:

Input: s = "3[a2[c]]"

Output: "accaccacc"

Example 3:

Input: s = "2[abc]3[cd]ef"

Output: "abcabccdcdcdef"

Constraints:

  • 1 <= s.length <= 30
  • s consists of lowercase English letters, digits, and square brackets '[]'.
  • s is guaranteed to be a valid input.
  • All the integers in s are in the range [1, 300].

Idea

Scan the string once and use two stacks to handle the nested brackets: one stores the repeat counts and the other stores the partial strings built before each '['.

Digits build up the current count \(k\), and letters are appended to the current string. On '[', push \(k\) and the current string onto the stacks, then start a fresh string. On ']', pop the count and the previous string, and append the current string to the previous one \(k\) times; the result becomes the current string.

Time complexity: \(O(n + d \cdot L)\), Space complexity: \(O(n + L)\), where \(n\) is the length of s, \(L\) is the length of the decoded string, and \(d\) is the maximum nesting depth of the brackets

Pseudo Code

countStack = empty stack;
stringStack = empty stack;
cur = empty string builder;
k = 0;
for (c in s) {
    if (c is a digit) {
        k = k * 10 + (c - '0');
    }
    else if (c == '[') {
        countStack.push(k);
        stringStack.push(cur);
        cur = empty string builder;
        k = 0;
    }
    else if (c == ']') {
        repeat = countStack.pop();
        prev = stringStack.pop();
        for (i = 0; i < repeat; i++) {
            prev.append(cur);
        }
        cur = prev;
    }
    else {
        cur.append(c);
    }
}
return cur.toString();