83. Decode a repeated string
A short way to write repeated text is a count followed by the text in square brackets: 3[ab] stands for ababab.
Repeats can sit inside each other: 2[a3[b]] is 2[abbb], which is abbbabbb.
Write a function decode(text) that takes text written this way and returns it written out in full:
- A count is a whole number of one or more digits, always followed by
[:10[x]is ten x's. - Letters outside any brackets stay as they are, wherever they are:
x2[y]zisxyyz. - Brackets always come in matching pairs, and empty brackets stand for nothing:
3[]is"".
Example 1
Input
text = "3[ab]"Output
"ababab"Explanationab, three times.
Example 2
Input
text = "2[a3[b]]c"Output
"abbbabbbc"ExplanationThe inner 3[b] first: 2[abbb], then c.
Example 3
Input
text = "x10[y]"Output
"xyyyyyyyyyy"ExplanationA two-digit count: ten y's after the x.
Constraints
texthas 0 to 100 characters: lower-case letters, digits and square brackets, always written as described.- Counts are from 1 to 99, and the text written out is at most 1000 characters.
Submit also runs 9 more tests you can't see.
- Read the text one character at a time, building the decoded text so far. Digits build a count:
count = count * 10 + int(ch)handles counts of more than one digit. - At
[, a new repeat starts: push the text so far and the count onto a stack, then start both afresh. - At
], pop the text from before and the count, and the decoded text becomesbefore + current * count. Nesting works because the inner]comes first.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
def decode(text):
"""Write out a string with counted repeats.
text: str, where k[...] means ... repeated k times
Returns: str, the text written out in full
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.