MediumStringStackRecursion

Decode String

LeetCode
1 approach, code in all languages

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 ≤ 30
  • s consists of lowercase English letters, digits, and square brackets
  • 1 ≤ k ≤ 300 for every repeat count
  • The input is guaranteed to be a valid encoding
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now