题目
字符串压缩。利用字符重复的次数,编写一种方法,实现基本的字符串压缩功能。
比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
思路
双指针定位相同字符的起始和终止位置。
class Solution:def compressString(self, S: str) -> str:# 双指针compress = ''i, j = 0, 0while i < len(S) or j < len(S):if j < len(S) and S[j] == S[i]:j += 1else:length = j - icompress += S[i] + str(length)i = jreturn compress if len(compress) < len(S) else S
