3163. String Compression III
Description
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"tocomp. - For prefix
"aaaaa", append"5"followed by"a"tocomp. - For prefix
"bb", append"2"followed by"b"tocomp.
Constraints:
1 <= word.length <= 2 * 105wordconsists only of lowercase English letters.
Solutions
Solution 1: Two Pointers
Thinking
Compression writes a count (at most \(9\)) plus the character for each run. Manual indices often mishandle splits at \(9\).
groupby already yields runs; each run is then cut into chunks of size at most \(9\).
For a run of length \(k\) append str(x)+c with \(x=\min(9,k)\) until \(k\) is exhausted.
We can use two pointers to count the consecutive occurrences of each character. Suppose the current character \(c\) appears consecutively \(k\) times, then we divide \(k\) into several \(x\), each \(x\) is at most \(9\), then we concatenate \(x\) and \(c\), and append each \(x\) and \(c\) to the result.
Finally, return the result.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Where \(n\) is the length of the
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
Solution 2: Two Pointers
Thinking
Method 1 uses a grouping helper. Two pointers can cut on a letter change or when the run reaches \(9\), without intermediate lists.
Keep the run start \(j\). When \(i\) hits the end, a new letter, or length \(9\), emit \(i-j\) and \(word[j]\) and set \(j=i\).
The scan ends at \(n\). Same linear bound, closer to the “at most nine” wording.
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
Solution 3: RegExp
Thinking
Two pointers still encode the split by hand. The pattern (.)\1{0,8} matches one to nine equal characters.
A global search swallows each such run; the count is the match length.
Append len(m[0]) and the captured letter. The result matches the previous methods with less arithmetic.
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |