Plain LIFO Stack

Decode String

Medium
Solve it on LeetCode ↗

The problem

Decode strings like "3[a2[c]]" → "accaccacc": k[encoded] means the bracket content repeats k times; nesting is arbitrary.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Maintain currentString, currentNum, and a stack of (savedString, savedNum) pairs.
  2. 2Digit → build currentNum. Letter → append to currentString.
  3. 3"[" → push the pair, reset both.
  4. 4"]" → pop (prev, k); currentString = prev + currentString.repeat(k).
  5. 5currentString at the end is the answer.

Key insight

Each "[" opens a nested subproblem whose context must be restored on "]" — saving (string, count) pairs on a stack is exactly a manual recursion.

The solution

Watch out for

  • Multi-digit counts ("100[a]") require num = num*10 + digit, not overwrite.
  • Repeated string concatenation is quadratic in some languages — join lists if inputs are hostile.