思路
雙指針,一個輔助指針用來計數
代碼
class Solution(object):
def compressString(self, S):
"""
:type S: str
:rtype: str
"""
n = len(S)
res = []
i = 0
while(i<n):
j = i
while(j<n and S[j] ==S[i]) :
j +=1
res +=S[i]
res+=str(j-i)
i= j
if len(res)<len(S):
return ''.join(res)
else:
return S