Program to encode a string in normal form to its run-length form in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s. We have to encode this by using run-length encoding technique. 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.

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

To solve this, we will follow these steps −

  • res := blank string
  • tmp := first character of s
  • count := 1
  • for i in range 1 to size of s, do
    • if s[i] is not same as tmp, then
      • res := res concatenate count concatenate tmp
      • tmp := s[i]
      • count := 1
    • otherwise,
      • count := count + 1
  • return res concatenate count concatenate tmp

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, s):
      res = ""
      tmp = s[0]
      count = 1
      for i in range(1,len(s)):
         if s[i] != tmp:
            res += str(count) + tmp
            tmp = s[i]
            count = 1
            count += 1
      return res + str(count) + tmp
ob = Solution() print(ob.solve("BBBBAAADDCBB"))




Published on 05-Oct-2020 06:31:27