01.06. Compress String
Description
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).
Example 1:
Input: "aabcccccaaa" Output: "a2b1c5a3"
Example 2:
Input: "abbccd" Output: "abbccd" Explanation: The compressed string is "a1b2c2d1", which is longer than the original string.
Note:
0 <= S.length <= 50000
Solutions
Solution 1: Two Pointers
Thinking
The compressed form concatenates each run’s character and length, and is kept only if it is shorter. Counting a run from every index is still linear but repeats work.
Each maximal run needs to be reported once, so the task reduces to locating run boundaries.
groupby (or explicit two pointers) emits each run as a character plus its length into \(t\), then the shorter of \(S\) and \(t\) is returned. Each character is visited once, which is the two-pointer grouping described in the write-up.
We can use two pointers to find the start and end positions of each consecutive character, calculate the length of the consecutive characters, and then append the character and length to the string \(t\).
Finally, we compare the lengths of \(t\) and \(S\). If the length of \(t\) is less than \(S\), we return \(t\), otherwise we return \(S\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string.
1 2 3 4 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |