Python Solution


  • 0
    P
    class Solution(object):
        def compress(self, chars):
            """
            :type chars: List[str]
            :rtype: int
            """
            n = len(chars)
            index, result_index = 1, 0
            current_char, current_char_count = chars[0], 1
            while index < n:
                if current_char != chars[index]:
                    if current_char_count == 1:
                        # do nothing
                        chars[result_index] = current_char
                        result_index += 1
                    else:
                        chars[result_index] = current_char
                        for c in str(current_char_count):
                            chars[result_index+1] = c
                            result_index += 1
                        result_index += 1
                    current_char = chars[index]
                    current_char_count = 1
                else:
                    current_char_count += 1
                index += 1
                
            if current_char_count == 1:
                chars[result_index] = current_char
                result_index += 1
            else:
                chars[result_index] = current_char
                for c in str(current_char_count):
                    chars[result_index+1] = c
                    result_index += 1
                result_index += 1
            return result_index
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.