Decode String
1 approach, code in every language
Problem description
You are given an encoded string that uses the format k[content], where the bracketed content is repeated exactly k times. Encodings can be nested, so a bracketed section may itself contain more k[content] pieces. Return the fully expanded, decoded string.
The input is always well formed: brackets are balanced, repeat counts are positive integers, and letters outside brackets simply appear as themselves. There are no stray digits that are not tied to a bracketed block.
Example 1
Input: s = "2[ab]3[c]"
Output: "ababccc"
"ab" repeats twice and "c" repeats three times, concatenated in order.
Example 2
Input: s = "2[a2[b]]"
Output: "abbabb"
The inner "2[b]" becomes "bb", giving "abb", and the outer count doubles that to "abbabb".
Constraints
1 ≤ s.length ≤ 30s consists of lowercase English letters, digits, and square brackets1 ≤ k ≤ 300 for every repeat countThe input is guaranteed to be a valid encoding
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Expand the Weave Pattern is our own problem on the technique behind Decode String: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free