题目描述
解法
这道题很简单,就是计数
有两个地方要注意:
- 遇到新的字符后,count记得置回1
- 因为是遇到新的不同的字符后才会触发结束计数,添加到新字符串的操作。所以计算到最后一个字符时,不会触发添加才做,计完数了就直接退出for循环,因此在for循环外面再添加一次 添加 操作。
class Solution:
def compressString(self, S: str) -> str:
if not S:
return ''
newstr = []
tmp = S[0]
count = 0
for i in S:
if i == tmp:
count += 1
else:
newstr.append(tmp)
newstr.append(str(count))
tmp = i
count = 1
newstr.append(tmp)
newstr.append(str(count))
newstr = ''.join(newstr)
if len(newstr)>=len(S):
return S
else:
return newstr