OK, a sequel!
I like:
- We have two views of the same array.
- We can start at 1 in the for-loop
- Opportunity for invariants to help our loop-based reasoning.
- Things get much simpler with the helper function (i.e., I made a lot of bugs until I decided to use a helper function).
I don’t think I’m biased to say this one requires a bit of careful thought!
class Solution(object):
def commitLetter(self, chars, c, i, count):
assert(count > 0)
chars[i] = c
i += 1
if count > 1:
w = str(count)
for t in w:
chars[i] = t
i += 1
return i
def compress(self, chars):
if len(chars) == 0: return []
count = 1
j = 0
lastChar = chars[0]
for i in range(1, len(chars)):
if chars[i] == lastChar:
count += 1
else:
j = self.commitLetter(chars, lastChar, j, count)
lastChar = chars[i]
count = 1
j = self.commitLetter(chars, lastChar, j, count)
return j