The problem. A string is encoded with the rule k[text], meaning text repeated exactly k times. Encodings can be nested, and plain letters can appear anywhere. Return the decoded string. The input is always valid: k is a positive integer (possibly with several digits), brackets are balanced, and digits only ever appear as repeat counts.
Input: "3[a]2[bc]" Output: "aaabcbc"
Input: "3[a2[c]]" Output: "accaccacc"
Input: "2[abc]3[cd]ef" Output: "abcabccdcdcdef"Nesting is the giveaway. An inner bracket must be fully decoded before the bracket around it can be repeated — the most recently opened bracket finishes first. A stack (or recursion, which is a stack in disguise) is the tool.
Free account
Sign up to read the rest of this lesson: 5 more sections, 3 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come