Decode String

Medium Stack & Queue AI round

s is an encoded string: small letters, and groups written k[...], where k is a whole number, the group's count, and the brackets hold an encoded string of their own.

A group k[...] stands for what its brackets hold, decoded, written out k times in a row. Groups can sit inside groups, and letters outside every group stand for themselves.

Return the decoded string.

Example 1

Input: s = "2[x3[yz]]w"
Output: "xyzyzyzxyzyzyzw"

The group 3[yz] is yzyzyz. The group around it holds x and then that, xyzyzyz, written out 2 times; w comes after.

Example 2

Input: s = "ab12[c]"
Output: "abcccccccccccc"

The count 12 has two digits: ab, then twelve c's.

Example 3

Input: s = "q"
Output: "q"

Constraints

  • 1 ≤ s.length ≤ 10⁵
  • s holds only small letters, digits and the brackets [ and ], and is a valid encoding: every count is followed by [, every [ comes after a count and has its ], and no brackets are empty
  • every count k is a whole number from 1 to 999, written without leading zeros
  • The decoded string has at most 10⁵ letters

Watch the explanation

More Stack & Queue

All Stack & Queue problems