题目

字符串压缩。利用字符重复的次数,编写一种方法,实现基本的字符串压缩功能。
比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

image.png

思路

双指针定位相同字符的起始和终止位置。

  1. class Solution:
  2. def compressString(self, S: str) -> str:
  3. # 双指针
  4. compress = ''
  5. i, j = 0, 0
  6. while i < len(S) or j < len(S):
  7. if j < len(S) and S[j] == S[i]:
  8. j += 1
  9. else:
  10. length = j - i
  11. compress += S[i] + str(length)
  12. i = j
  13. return compress if len(compress) < len(S) else S