如题:
思路:
定义两个变量 当前压缩字符ch 和当前压缩字符计数 cnt = 1
定义ans 作为最终的结果返回 遍历整个字符串
如果第一个是 a 则设置为当前压缩字符为a 当前压缩字符计数为1
第二个字符还是a 与当前压缩字符一致 那么压缩字符计数就更新为2
第三个字符是b 与当前压缩字符不一致 那么要将之前的压缩字符结果保存到ans中 即a2 那么当前压缩字符变为b 当前压缩字符计数为1
第四个字符照旧
最后还要有一个判断 返回长度较小的字符串
代码为
class Solution:
def compressString(self, S:str) -> str:
if not S:
return ""
ch = S[0]
cnt = 0
ans = ''
for c in S:
if c == ch:
cnt += 1
else:
ans += ch + str(cnt)
ch = c
cnt = 1
ans += ch + str(cnt)
return ans if len(ans) < len(S) else S