Skip to the code
cf.
+25 XP

#253 Expand Repeat Markers

medium

A tiny templating language for generating test fixtures writes repeated text as k[text], meaning text written k times. Markers can be nested: 2[a3[b]] is abbbabbb.

Write expand(template) that returns the fully expanded string. Every number is followed by a [, every [ has a matching ], and letters outside markers are copied as they are.

Example 1

Input: template = "2[x]3[yz]"
Output: "xxyzyzyz"

xx followed by yzyzyz.

Example 2

Input: template = "3[a2[c]]"
Output: "accaccacc"

The inside a2[c] is acc, written 3 times.

Constraints

  • 0 <= template.length <= 30
  • 1 <= k <= 300
  • The expanded string has at most 10^5 characters.
  • template has lowercase letters, digits, [, and ].
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).