Tuesday, January 6, 2015

String compression

Given a string with repeated characters find out a way to compress the string with a count of number of times the character got appended. For example a string like "aabbbccdeeefff" would become like "a2b3c2de3f3" after compression !
#! /usr/env/path python
sampleStr = "aabbbccdeeefff"
#compress the string a2b3c2de3f3
def compressString(sampleStr):
count = 0
temp = sampleStr[0]
compressedString = ""
for i in range(len(sampleStr)):
if (sampleStr[i] == temp):
count += 1
temp = sampleStr[i]
else:
if (count > 1):
compressedString = compressedString + temp + str(count)
else:
compressedString = compressedString + temp
temp = sampleStr[i]
count = 1
if (count > 1):
compressedString = compressedString + temp + str(count)
else:
compressedString = compressedString + temp
return compressedString
print(compressString(sampleStr))
view raw compress.py hosted with ❤ by GitHub

No comments:

Post a Comment