Show problems as
Classic problem #394MediumStringStackRecursion

Decode String

Real-world version: Expand the Weave Pattern
Tracked in this browser only
Read Decode String on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstRegular Expressions · Strings, animated step by step

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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

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