Given a string word
, compress it using the following algorithm:
- Begin with an empty string
comp
. Whileword
is not empty, use the following operation:- Remove a maximum length prefix of
word
made of a single characterc
repeating at most 9 times. - Append the length of the prefix followed by
c
tocomp
.
- 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 * 105
word
consists only of lowercase English letters.
Approach 01:
-
C++
-
Python
#include <string> using namespace std; class Solution { public: string compressedString(const string& inputWord) { const int wordLength = inputWord.length(); string compressedWord; for (int i = 0, j = 0; i < wordLength; i = j) { int count = 0; while (j < wordLength && inputWord[j] == inputWord[i] && count < 9) { ++j; ++count; } compressedWord += to_string(count) + inputWord[i]; } return compressedWord; } };
class Solution: def compressedString(self, inputWord: str) -> str: wordLength = len(inputWord) compressedWord = '' i = 0 while i < wordLength: count = 0 j = i while j < wordLength and inputWord[j] == inputWord[i] and count < 9: j += 1 count += 1 compressedWord += str(count) + inputWord[i] i = j return compressedWord
Time Complexity
- Main Loop:
The function iterates through the input string
inputWord
using two pointers,i
andj
. Each character ininputWord
is processed at most once, making the loop run in \( O(N) \), where \( N \) is the length ofinputWord
. - Overall Time Complexity:
The overall time complexity is \( O(N) \).
Space Complexity
- Compressed String:
The
compressedWord
string holds the compressed output, which, in the worst case, could be nearly as long as the input if each character is unique or grouped in short sequences. This results in \( O(N) \) space complexity. - Other Variables:
Other variables such as
count
andj
are constants and do not add significant space usage. - Overall Space Complexity:
The overall space complexity is \( O(N) \).