443. String Compression

Solution:

  • pretty easy once you get the hang of it but it took quite a bit of time
  • gotta take care of the edge cases. like when character is repeated just once/more than 9 times.
  • gotta make sure to keep track of the current index (which is the returning value, ie the length) and also make sure that the current index is set for both the alphabet and the count of the alphabet.
class Solution:
    def compress(self, chars: List[str]) -> int:
        cur = i = 0
        while i < len(chars):
            j = i + 1
            while j < len(chars) and chars[i] == chars[j]:
                j += 1
            cnt = j - i
            
            chars[cur] = chars[i]
            cur += 1
            if cnt > 1:
                for let in str(cnt):
                    chars[cur] = let
                    cur += 1
            i += cnt
        return cur