LC 0443 [M] String Compression
Code with Senpai edited this page Feb 14, 2022
·
1 revision
class Solution(object):
def compress(self, chars):
# make it a bit faster
if len(chars) < 2:
return len(chars)
# pointers: r (main iterator), l (start of contiguous), write (write pointer)
# the start position of the contiguous group of characters we are currently reading.
l = 0
# position to Write Next
# we start with 0 then increase it whenever we write to the array
write = 0
# we go through each caharcter till we fiand a pos where the next is not equal to it
# then we check if it has appeared more than once using the anchor and r(read) pointers
# 1. iterate till we find a diffrent char
# 2. record the no. of times the current char was repeated
for r, c in enumerate(chars):
# check if we have reached the end or a different char
# check if we are end or the next char != the current
if (r + 1) == len(chars) or c != chars[r+1]:
chars[write] = c
write += 1
# check if char has been repeated
# have been duplicated if the read pointer is ahead of the anchor pointer
if r > l:
# check no. of times char has been repeated
repeated_times = r - l + 1
# write the number
for num in str(repeated_times):
chars[write] = num
write += 1
# move the anchor to the next char in the iteration
l = r + 1
return write
footer