题目:
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
示例1:
输入:"aabcccccaaa"
输出:"a2b1c5a3"
分析: 给定一个快慢指针,遍历到字符串尾部即可,时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( 1 ) O(1) O(1)
class Solution:
def compressString(self, S: str) -> str:
slow = fast = 0
new_str = ''
if not S:
return S
for fast in range(1, len(S)):
if S[fast] != S[slow]:
new_str = new_str + S[slow] + str(fast - slow)
slow = fast
new_str = new_str + S[slow] + str(fast - slow + 1)
if len(new_str) >= len(S):
new_str = S
return new_str