输入一串字符,请编写一个字符串压缩程序,将字符串中连续出现的重复字母进行压缩,并输出压缩后的字符串。
例如:
aac 压缩为 1ac
xxxxyyyyyyzbbb 压缩为 3x5yz2b
输入描述:
任意长度字符串
输出描述:
压缩后的字符串
示例1
输入
xxxxyyyyyyzbbb
输出
3x5yz2b
import sys
s = sys.stdin.readline().strip()
def zipstr(s):
l=list(s)
res=[0]
# res.append(l[0])
count=0
for i in range(0,len(l)):
if l[i]==res[-1]:
count=count+1
else:
if count>=1:
res.insert(-1,str(count))
res.append(l[i])
count=0
if count>=1:
res.insert(-1,str(count))
res.pop(0)#删除一开始为了方便加的0
return "".join(res)
print(zipstr(s))