Given a string word, compress it using the following algorithm.
Begin with an empty string comp. While word is not empty, apply this operation:
-
Remove a maximum length prefix of
word
made of a single character
c
repeating at most 9 times.
-
Append the length of the prefix followed by
c
to
comp
.
Return the string comp.
Function Signature
def compressed_string(word: str) -> str:
Rules
-
The count is always one digit from 1 to 9 and comes before the character. A single character is written with a count of 1, as in
"1a"
.
-
A run longer than 9 is split. Its first 9 characters become
"9c"
, and the rest are handled by the following operations.
-
Only consecutive characters form a prefix, so separate runs of the same letter are encoded separately.
Constraints
-
1 <= len(word) <= 2 * 10^5
-
word
consists only of lowercase English letters.
Examples
Input: word = "abcde"
Output: "1a1b1c1d1e"
Every run has length 1, so each character is written with a count of 1.
Input: word = "aaaaaaaaaaaaaabb"
Output: "9a5a2b"
There are 14 'a' characters followed by 2 'b' characters. The first operation removes 9 'a' ("9a"), the second removes the remaining 5 ("5a"), and the last removes "bb" ("2b").
Input: word = "aabaa"
Output: "2a1b2a"
The two runs of 'a' are separated by 'b', so each one is its own prefix when the loop reaches it.