LeetCode--Python解析【String Compression】(443)

题目:

方法:

class Solution:
    def compress(self, chars):
        """
        :type chars: List[str]
        :rtype: int
        """
        n = len(chars)
        i , count = 0 , 1
        for j in range(1,n+1):
            if j < n and chars[j] == chars[j-1]:
                count += 1
            else:
                chars[i] = chars[j-1]
                i += 1
                if count > 1:
                    for m in str(count):
                        chars[i] = m
                        i += 1
                count = 1
        return i

分别设置两个指针,i和j

i为更改后的chars的长度,j为当前便利chars的位置

count为重复次数

当字符串结束重复后

通过移动指针i,将count写入chars

最后返回i的位置,即新的字符串长度

猜你喜欢

转载自blog.csdn.net/ZJRN1027/article/details/81188486