My code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution:
    def compress(self, chars: List[str]) -> int:
        element_ptr, count_ptr = 0, 0
        current_char = None
        current_len = 0
        
        while count_ptr < len(chars):
            if chars[count_ptr] != current_char:
                # a new character
                if current_len > 1:
                    len_str = []
                    while current_len:
                        len_str.append(str(current_len % 10))
                        current_len = current_len // 10
                    for lstr in len_str[::-1]:
                        chars[element_ptr] = lstr
                        element_ptr += 1
                chars[element_ptr] = chars[count_ptr]
                element_ptr += 1
                current_char = chars[count_ptr]
                current_len = 1
            else:
                # the same character
                current_len += 1
            count_ptr += 1
        
        if current_len > 1:
            len_str = []
            while current_len:
                len_str.append(str(current_len % 10))
                current_len = current_len // 10
            for lstr in len_str[::-1]:
                chars[element_ptr] = lstr
                element_ptr += 1
        return element_ptr

other code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def compress(self, chars: List[str]) -> int:
        d=[]
        c=1
        for i in range(1,len(chars)):
            if chars[i]==chars[i-1]:
                c+=1
            else:
                d.append([chars[i-1],c])
                c=1
        d.append([chars[-1],c]) 
        i=0
        for k,v in d:
            chars[i]=k
            i+=1
            if v>1:
                for item in str(v):
                    chars[i]=str(item)
                    i+=1
        return i