Problem description

You are given an encoded string that uses the format k[content], where the bracketed content is repeated exactly k times. Encodings can be nested, so a bracketed section may itself contain more k[content] pieces. Return the fully expanded, decoded string.

The input is always well formed: brackets are balanced, repeat counts are positive integers, and letters outside brackets simply appear as themselves. There are no stray digits that are not tied to a bracketed block.

Example 1

Input: s = "2[ab]3[c]"

Output: "ababccc"

"ab" repeats twice and "c" repeats three times, concatenated in order.

Example 2

Input: s = "2[a2[b]]"

Output: "abbabb"

The inner "2[b]" becomes "bb", giving "abb", and the outer count doubles that to "abbabb".

Constraints

  • 1 ≤ s.length ≤ 30
  • s consists of lowercase English letters, digits, and square brackets
  • 1 ≤ k ≤ 300 for every repeat count
  • The input is guaranteed to be a valid encoding

After the pattern

Now solve one you haven't seen.

Expand the Weave Pattern is our own problem on the technique behind Decode String: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free