Decode String

Medium · Stack & Strings · String · Stack · Recursion

Problem

A string is encoded with the rule k[text]: the part inside the brackets is written out k times in a row. Rules can nest, so 3[a2[c]] means acc three times, accaccacc. Given an encoded string s, return it decoded.

s is always well formed: the brackets match, every [ comes straight after a whole number k ≥ 1, and digits appear only in those counts, never in the text itself. A count can have more than one digit, as in 12[ab], and letters can sit before, between and after groups at any level.

Examples

Input: s = "3[a]2[bc]"
Output: "aaabcbc"

a three times, then bc twice.

Input: s = "3[a2[c]]"
Output: "accaccacc"

Inside out: 2[c] is cc, so a2[c] is acc, and three of those make accaccacc.

Constraints

Approaches

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…