All problems
0037MediumStringStackRecursion

Expand the Weave Pattern

Tracked in this browser only
Write code

Trains the technique from

LeetCode 394Decode String

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A loom is driven by a shorthand pattern. Each lowercase letter stands for one pass of a particular yarn, and a repeated stretch is written compactly as a count immediately followed by the stretch it applies to, wrapped in square brackets: 4[xy] weaves the stretch xy four times in a row.

A bracketed stretch may itself contain counts and brackets, in which case the inner shorthand is expanded first and the whole result of the outer bracket is then repeated. Counts may have more than one digit. Every digit in pattern belongs to a count that is attached to a bracketed stretch, so no digit is ever part of the woven output.

Return the fully written-out sequence of yarn passes. You may assume pattern is well formed: brackets are balanced and each opening bracket is preceded by a count.

Examples

Example 1

Input
pattern = "4[xy]z"
Output
"xyxyxyxyz"

The stretch xy is woven four times and the trailing z is woven once.

Example 2

Input
pattern = "2[b3[ca]]"
Output
"bcacacabcacaca"

The inner bracket becomes cacaca, so the outer stretch is bcacaca, and that whole stretch is woven twice.

Example 3

Input
pattern = "12[q]"
Output
"qqqqqqqqqqqq"

The count spans two digits, so q is woven twelve times rather than once then twice.

Constraints

  • 1 <= pattern.length <= 30
  • pattern contains lowercase English letters, digits and the characters '[' and ']' only
  • pattern is well formed
  • Every count in pattern is between 1 and 300

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def expand_weave(pattern: str) -> str:
Java
public String expandWeave(String pattern)
September 7
Apply