Decode a Run-Length Nested Encoded String

Implement decodeString

Given an encoded string s in the form k[encoded_string] (where k is a positive integer, possibly nested arbitrarily deep), decode it by repeating each bracketed substring k times. Recursively parsing this works, but finding each bracket's match by scanning forward wastes effort re-treading the string. A single-pass approach with two stacks avoids that entirely: track the string being built at the current nesting level, and whenever a new level opens ('['), push the pending repeat count and the string built so far, then start fresh. Whenever a level closes (']'), pop both back off and fold the finished level in — repeat it and prepend what came before. The stack always knows exactly where to resume, with no need to ever locate a matching bracket's position in advance.

Example 1:

Input: s = "5[q]3[rst]w"

Output: "qqqqqrstrstrstw"

Example 2:

Input: s = "3[cd2[e]]"

Output: "cdeecdeecdee"

Example 3:

Input: s = "4[op]qr"

Output: "opopopopqr"

+ 5 hidden test cases run on Submit.

Constraints:

  • 1 ≤ s.length ≤ 15
  • s is a valid encoding: k[encoded_string], where k is a positive integer and encoded_string only contains lowercase letters, digits, and further valid k[...] patterns
  • The decoded output length never exceeds 100 characters

s =

5[q]3[rst]w