Stacks and Queues Matching and cancelling
202. Decode String
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"
"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]"
"abcccccccccccc"Explanation: The count is twelve, so c is written 12 times after ab.
Example 3
Input: s = "1[a1[b]]c"
"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.
Constraints
1 ≤ s.length ≤ 105sholds lowercase English letters, digits and the brackets[and].sis 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 ≤ 105for every countk, 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.