Given an input string, write a function that returns the Run Length Encoded string for the input string. For example, if the input string is ‘wwwwaaadexxxxxx’, then the function should return ‘w4a3d1e1x6’.
Examples:
Input : str = 'wwwwaaadexxxxxx'
Output : 'w4a3d1e1x6'
This problem has existing solution please refer Run Length Encoding link. Here we will solve this problem quickly in python using OrderedDict. Approach is very simple, first we create a ordered dictionary which contains characters of input string as key and 0 as their default value, now we run a loop to count frequency of each character and will map it to it’s corresponding key.
Implementation:
Python3
from collections import OrderedDict
def runLengthEncoding(input):
dict=OrderedDict.fromkeys(input, 0)
for ch in input:
dict[ch] += 1
output = ''
for key,value in dict.items():
output = output + key + str(value)
return output
if __name__ == "__main__":
input="wwwwaaadexxxxxx"
print (runLengthEncoding(input))
|
Another code:
Python3
def encode(message):
encoded_message = ""
i = 0
while (i <= len(message)-1):
count = 1
ch = message[i]
j = i
while (j < len(message)-1):
if (message[j] == message[j+1]):
count = count+1
j = j+1
else:
break
encoded_message=encoded_message+str(count)+ch
i = j+1
return encoded_message
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)
|
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
You'll access excellent video content by our CEO, Sandeep Jain, tackle common interview questions, and engage in real-time coding contests covering various DSA topics. We're here to prepare you thoroughly for online assessments and interviews.
Ready to dive in? Explore our free demo content and join our DSA course, trusted by over 100,000 geeks! Whether it's
DSA in C++,
Java,
Python, or
JavaScript we've got you covered. Let's embark on this exciting journey together!