443. String Compression

Easy

Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array. Follow up: Could you solve it using only O(1) extra space?

😇 Solution

class Solution:
    def stringCompression(s):
        i = 0
        ans = ''
        while(i < len(s)):
            count = 0
            c = s[i]
            while(c == s[i]):
                i += 1
                count += 1
                if i == len(s):
                    break
            ans += c
            if count != 1:
                ans += str(count)
        return ans if len(ans) <= len(s) else s
    
    def compress(self, chars: List[str]) -> int:
        
        s = ''
        for c in chars:
            s += c
        ans =  Solution.stringCompression(s)
        for i,a in enumerate(ans):
            chars[i] = a
        return len(ans)

Last updated

Was this helpful?