
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Encode String to Run-Length Form in Python
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
- if s[i] is not same as tmp, then
- return res concatenate count concatenate tmp
Let us see the following implementation to get better understanding −
Example
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 else: count += 1 return res + str(count) + tmp ob = Solution() print(ob.solve("BBBBAAADDCBB"))
Input
"BBBBAAADDCBB"
Output
4B3A2D1C2B
Advertisements