String Compression III Problem
#3163
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3163.
Given a string word, compress it using the following algorithm:
- Begin with an empty string
comp. Whilewordis not empty, use the following operation:- Remove a maximum length prefix of
wordmade of a single charactercrepeating at most 9 times. - Append the length of the prefix followed by
ctocomp.
- Remove a maximum length prefix of
Return the string comp.
Example 1:
Input: word = "abcde"
Output: "1a1b1c1d1e"
Explanation:
Initially, comp = "". Apply the operation 5 times, choosing "a", "b", "c", "d", and "e" as the prefix in each operation.
For each prefix, append "1" followed by the character to comp.
Example 2:
Input: word = "aaaaaaaaaaaaaabb"
Output: "9a5a2b"
Explanation:
Initially, comp = "". Apply the operation 3 times, choosing "aaaaaaaaa", "aaaaa", and "bb" as the prefix in each operation.
- For prefix "aaaaaaaaa", append "9" followed by "a" to comp.
- For prefix "aaaaa", append "5" followed by "a" to comp.
- For prefix "bb", append "2" followed by "b" to comp.
Constraints:
1 <= word.length <= 2 * 10^5wordconsists only of lowercase English letters.
Solution
Approach: Run Counting
Scan the string and measure each run of equal characters. A run of length k is cut into chunks of at most 9; each chunk x is written as x followed by the character.
Complexity: time O(n), space O(n).
from itertools import groupby
class Solution:
def compressedString(self, word: str) -> str:
g = groupby(word)
ans = []
for c, v in g:
k = len(list(v))
while k:
x = min(9, k)
ans.append(str(x) + c)
k -= x
return "".join(ans)