Start learning free

LESSON 478 OF 677 · STACK

Decode String

Practice O(n)

You get a string s in a short form. In it, k[text] means text written k times in a row.

Return the full string, with every group written out.

A group can sit inside another group. The input is always valid. Brackets always match. There are no spaces. Digits only appear as a repeat count, right before a [. So you will never see 5k or 2[7].


Example 1:

Input: s = "2[ha]3[o]"
Output: "hahaooo"

Example 2:

Input: s = "2[m3[e]]"
Output: "meeemeee"
Explanation: "3[e]" becomes "eee".
The outer group then holds "meee".
Two copies of it give "meeemeee".

Example 3:

Input: s = "a10[b]c"
Output: "abbbbbbbbbbc"
Explanation: A count can have more than one digit.
Here "b" is written 10 times.
Letters outside any group stay as they are.

Constraints:

  • s has 1 to 40 characters.
  • Each character is a lowercase letter, a digit, [ or ].
  • Every repeat count is a whole number from 1 to 300.
  • The decoded string has at most 100,000 characters.

STEP 1 OF 16
    Ctrl + Enter to check