smj007

string compression

Sep 1st, 2025
370
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.53 KB | None | 0 0
  1. class Solution:
  2.     def compress(self, chars: List[str]) -> int:
  3.        
  4.         read = 0
  5.         write = 0
  6.  
  7.         while read < len(chars):
  8.  
  9.             char = chars[read]
  10.             count = 0
  11.             while read < len(chars) and char == chars[read]:
  12.                 read += 1
  13.                 count += 1
  14.  
  15.             chars[write] = char
  16.             write += 1
  17.  
  18.             if count > 1:
  19.                 for c in str(count):
  20.                     chars[write] = c
  21.                     write += 1
  22.  
  23.         return write
Advertisement
Add Comment
Please, Sign In to add comment