oneby7

Stacks and Queues Matching and cancelling

202. Decode String

Medium

You are given an encoded string s. Return the decoded string.

The encoding has one rule: k[text] stands for text written k times in a row, where k is a positive whole number called the count. The text inside a pair of brackets can hold more encoded groups, so groups can sit inside each other. Letters outside every pair of brackets stay as they are. For example, 2[ab]c decodes to ababc, and 2[a2[b]] decodes to abbabb.

Answers are shown in double quotes.

Example 1

Input: s = "2[x3[yz]]w"

Output: "xyzyzyzxyzyzyzw"

Explanation: The inner group 3[yz] is yzyzyz, so the outer group holds xyzyzyz and writes it twice. The w is outside every bracket, so it is written once, at the end.

Example 2

Input: s = "ab12[c]"

Output: "abcccccccccccc"

Explanation: The count is twelve, so c is written 12 times after ab.

Example 3

Input: s = "1[a1[b]]c"

Output: "abc"

Explanation: A count of 1 writes its text once, so these brackets change nothing.

Check your understanding

Work out the answer for this input before you write any code.

s = "2[a3[b]c]"

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds lowercase English letters, digits and the brackets [ and ].
  • s is a valid encoding: every count is followed by [, every [ has a count before it and a matching ], no pair of brackets is empty, and digits appear only in counts.
  • 1 ≤ k ≤ 105 for every count k, written without leading zeros.
  • Brackets nest at most 1000 deep.
  • The decoded string has at most 106 characters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.