def compress(self, chars):
    """
    :type chars: List[str]
    :rtype: int
    """
    prev, write, length = 0, 0, len(chars)
    for index, char in enumerate(chars):
        if index == length - 1 or char != chars[index+1]:
            chars[write] = char
            write += 1
            if index > prev:
                for digit in str(index-prev+1):
                    chars[write] = digit
                    write += 1
            prev = index+1
    return write
def compress(self, chars):
    prev, count = chars[0], 1
    write_pointer, list_size = 0, len(chars)
    for i in xrange(1, list_size):
        cur = chars[i]
        if cur == prev:
            count += 1
        else:
            if count > 1:
                repeat = str(count)
                for j in xrange(len(repeat)):
                    write_pointer += 1
                    chars[write_pointer] = repeat[j]
                count = 1
            write_pointer += 1
            chars[write_pointer] = cur
            prev = cur
    if count > 1:
        repeat = str(count)
        for j in xrange(len(repeat)):
            write_pointer += 1
            chars[write_pointer] = repeat[j]
    for k in xrange(write_pointer+1, list_size):
        chars.pop()

    return len(chars)

We will use separate pointersreadandwriteto mark where we are reading and writing from. Both operations will be done left to right alternately: we will read a contiguous group of characters, then write the compressed version to the array. At the end, the position of thewritehead will be the length of the answer that was written.

Algorithm

Let's maintainanchor, the start position of the contiguous group of characters we are currently reading.

Now, let's read from left to right. We know that we must be at the end of the block when we are at the last character, or when the next character is different from the current character.

When we are at the end of a group, we will write the result of that group down using ourwritehead.chars[anchor]will be the correct character, and the length (if greater than 1) will beread - anchor + 1. We will write the digits of that number to the array.

results matching ""

    No results matching ""