Compress the String
Level MEDIUM
Write a program to do basic string compression. For a character which is consecutively repeated more than once, replace consecutive duplicate occurrences with the count of repetitions.
For e.g. if a String has 'x' repeated 5 times, replace this "xxxxx" with "x5".
Note : Consecutive count of every character in input string is less than equal to 9.
Input Format :
Output Format :
Constraints :
Sample Input 1 :
Sample Output 1 :
Sample Input 2 :
Sample Output 2 :
a3b2cd2e5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
s=input() | |
res=[] | |
i=0 | |
while i<len(s): | |
count = 1 | |
j=i+1 | |
while j<len(s): | |
if s[i]==s[j]: | |
count+=1 | |
j+=1 | |
else:break | |
if count>1: | |
res.append(s[i]+str(count)) | |
else: | |
res.append(s[i]) | |
i=i+count | |
for i in range(0,len(res)): | |
print(res[i],end="") |
Comments
Post a Comment
Please give us your valuable feedback