Unfold the brackets
Expand a string where a number before a bracketed part means repeat it, and parts can sit inside parts. About 18 minutes.
A bracket is a smaller problem
The text 3[a2[c]] means: take the group inside the outer brackets and repeat it three times. That group is the letter a
followed by two copies of c, which is "acc". So the whole text decodes to "accaccacc".
The inside of a bracket is exactly the same kind of text, so decode it by calling the same function. Walk along the text. A letter is added as it is. A number is remembered. An opening bracket starts a recursive call that returns when it meets the matching closing bracket.
depth = best = 0
for ch in s:
if ch == "[":
depth += 1
best = max(best, depth)
elif ch == "]":
depth -= 1A 2: remember the count 2.
Return the position too
A recursive call decodes the inside of a bracket, but the outer call needs to know where to carry on afterwards: just past the matching closing bracket. So the call returns two things, the decoded text and the position where it stopped.
Numbers can have several digits, such as 12, so build them up digit by digit. Reset the count after using it.
What does 2[ab3[c]] decode to?
- Aabcccabccc
- Babcabc
- Cababccc
Show the answer
abcccabccc. Inside, 3[c] is ccc, so the group is abccc, repeated twice.
Unfold the brackets
s is an encoded string made of lowercase letters, digits and square brackets. A number k followed by a bracketed part means that part is repeated k times, and bracketed parts can be nested. The brackets are always balanced, and every number is directly followed by an opening bracket. Return the decoded string.
s = "3[a2[c]]" → "accaccacc"
1 ≤ length ≤ 60 · numbers are between 1 and 20 · the decoded length is at most 3,000