JavaScript required
We’re sorry, but Coda doesn’t work properly without JavaScript enabled.
Skip to content
Gallery
Algoschool
Algocircle
More
Share
Explore
Level 1
Arrays problems
https://leetcode.com/problems/string-compression/
https://leetcode.com/problems/string-compression/
class Solution:
def compress(self, chars: List[str]) -> int:
prev = chars[0]
count = 0
j = 0
for i in range(len(chars)):
if chars[i] == prev:
count += 1
else:
chars[j] = prev
j += 1
if count > 1:
digits = str(count)
for k in range(len(digits)):
chars[j] = digits[k]
j += 1
prev = chars[i]
count = 1
chars[j] = prev
j += 1
if count > 1:
digits = str(count)
for k in range(len(digits)):
chars[j] = digits[k]
j += 1
return j
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
Ctrl
P
) instead.