leetcode——2020-03月:字符串的壓縮

思路

雙指針,一個輔助指針用來計數

代碼

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章