压缩字符串
输入字符串str
例如 HHHEELLLOOOO压缩为H3E2L3O4
例子:
None ->None
'' -> ''
'ABBC' -> AB2C
假设:
字符串仅有ascii组成
大小写敏感
寻找连续出现的子串,并计算出现次数
def Compress(self, string):
alist = []
count = 0
if string is None:
return None
if string == '':
return ''
alist.append(string[0])
for i in range(1, len(string)):
if string[i] == alist[-1]:
count = count + 1
else:
if count != 0:
alist.append(str(count + 1))
alist.append(string[i])
count = 0
if count != 0:
alist.append(str(count+1))
return ''.join(alist)