# String RLE Compression

Asked 1 weeks ago, Updated 1 weeks ago, 2 views

When a string is very long, it is often necessary to compress it and shorten it. In this problem, given a string, we write a program that compresses a sequence of substrings with the same alphabet and outputs a result. For example, suppose the string is AAABBBBBCCCCDDDDEFFFF. When this string is compressed, it is compressed by writing down how many times the character appears on the part where the same character appears consecutively. That is, this string is compressed into 3A5B4C4DE3F. Since there is only one E, you do not write down one separately.

The first line is given the string to be compressed. The length of the string is less than 1000. The alphabets constructed in the string are uppercase.

This code is

``````s = input()
cnt=1
ans = ''
for i in range(0,len(s)-1):
if s[i] == s[i+1]:
cnt+=1
else :
if cnt>1 :
print(str(cnt)+s[i],end='')
cnt=1
elif cnt==1 :
print(''+s[i],end='')
cnt=1
``````

That's it. I have to print out the last letter, but it doesn't work. Help me

string python

2022-09-20 11:33

There is a problem with the code, but you can also write it as it is. You can calculate it by adding one character that you can't "never" come after the character you want to calculate.

``````s = input()
s = s + "\0" # end of string adds characters that can never appear.
cnt=1
ans = ''
for i in range(0,len(s)-1):
if s[i] == s[i+1]:
cnt+=1
else :
if cnt>1 :
print(str(cnt)+s[i], end='')
cnt=1
elif cnt==1 :
print(''+s[i],end='')
cnt=1
``````

2022-09-20 11:33

Popular Tags
python x 1175
android x 247
c x 235
java x 192
javascript x 106
mysql x 30
html x 27
node.js x 24
php x 21
list x 19