题目:
题解:
- 设置一个来存储压缩后的字符串变量temp1,一个计算当前字母出现次数的变量count(初始值为0);
- 初始化temp1为S[0], count加1;然后依次循环字符串S;如果当前字符和前一个字符相等,那么当前字符的重复次数+1;如果不相等,那么temp1中加入当前字符,当前字符串的次数置1;
- 最后temp1即是所求的压缩字符串。
代码如下:
class Solution:
def compressString(self, S):
if S == '':
return S
#定义一个临时存储的空间
temp1 = ''
count = 0
if temp1 == '':
temp1 += S[0]
count += 1
for i in range(1,len(S)):
if S[i] != S[i - count]:
temp1 += str(count)
temp1 += S[i]
count = 1
else:
count += 1
temp1 += str(count)
if len(temp1) < len(S):
return temp1
else:
return S