Program to decode a run-length form of string into normal form in Python


Suppose we have a string s. The s is a run-length encoded string, we have to find the decoded version of it. As we know, run-length encoding is a fast and simple method of encoding strings. The idea is as follows − The repeated successive elements (characters) as a single count and character. For example, if the string is like "BBBBAAADDCBB" would be encoded as "4B3A2D1C2B".

So, if the input is like s = "4B3A2D1C2B", then the output will be "BBBBAAADDCBB"

To solve this, we will follow these steps −

  • output := blank string
  • num:= blank string
  • for each character i in s, do
    • if i is alphabet, then
      • output := output + i*(num as number)
      • num:= blank string
    • otherwise,
      • num := num + i
  • return output

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      output = ""
      num=""
      for i in s:
         if i.isalpha():
            output+=i*int(num)
            num=""
         else:
            num+=i
      return output
ob = Solution() print(ob.solve("4B3A2D1C2B"))

Input

"4B3A2D1C2B"

Output

BBBBAAADDCBB

Updated on: 05-Oct-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements