327/670

327. Decode String

Medium

You are given an encoded string s built from a single compression rule: k[chunk] means the chunk between the square brackets is written out exactly k times in a row, where k is a positive integer (it may have several digits). Chunks can be nested — a bracketed chunk may itself contain more k[...] groups — and plain letters outside any brackets are copied through unchanged.

Return the fully decoded string.

The input is guaranteed well-formed: every [ has a matching ], every bracket group is preceded by a repeat count, digits appear only as repeat counts, and the decoded result is never astronomically large (see the constraints).

Example 1:

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

Output: "ababccc"

Explanation: "ab" is repeated twice, then "c" three times: "abab" + "ccc".

Example 2:

Input: s = "2[x3[y]]"

Output: "xyyyxyyy"

Explanation: The inner group decodes first: x3[y] → "xyyy". The outer 2[...] then doubles it.

Constraints:

  • 1 ≤ s.length ≤ 100
  • s consists of lowercase English letters, digits, and square brackets.
  • 1 ≤ k ≤ 300 for every repeat count k.
  • s is guaranteed to be a valid encoding, and the decoded string has at most 10⁵ characters.

Hints:

Nesting means the innermost bracket must be finished before the one around it — last opened, first closed. That order is exactly what a stack gives you.

Build the current chunk in a buffer. On "[", push the repeat count and the text built so far, then start fresh; on "]", pop both and set buffer = popped-text + buffer × popped-count. Accumulate counts digit by digit (k = k*10 + digit) so "10[a]" works.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: "ababccc"