Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to decode a run length encoded text, from string 'A4B3C2' to 'AAAABBBCC', my code now however works by decoding the number first then the letter, which gives me an output of ABBBBCCC instead of what I want 'AAAABBBCC'

What I have tried:

class Solution:
    def decode(self,s):
        res, n = "", ""
        for char in s:
            if char.isdigit():
                n += char
            elif n == "":
                res += char
            else:
                res += char * int(n)
                n = ""
        return res

ob = Solution() 
print(ob.decode("A4B3C2"))
Posted
Updated 9-Nov-22 18:16pm
v2

1 solution

What you need to do is:

1) Preset two variables to an empty string: last and result
2) Loop through each character in the input string
2.1) If the character is a digit, then add last that many times to result
2.2) Otherwise, set last to the character
3) After the loop, return result

Try that, and see how you go.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900