Sponsored
Sponsored
This approach involves iterating through the string and counting consecutive characters. For each new character, append the count and character to the output string. If the count reaches 9, append and reset it.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), as we store the result string separately.
1#include <string>
std::string compressString(const std::string& word) {
std::string result;
int i = 0;
while (i < word.length()) {
char current = word[i];
int count = 0;
while (i < word.length() && word[i] == current && count < 9) {
++i;
++count;
}
result += std::to_string(count) + current;
}
return result;
}
int main() {
std::cout << compressString("abcde") << std::endl;
std::cout << compressString("aaaaaaaaaaaaaabb") << std::endl;
return 0;
}
This C++ solution uses an iterative approach with a while-loop to construct the compressed string, using the std::string
class.
This approach is similar to the iterative approach but conceptualizes the counting as a sliding window over the input string. You increment the window until it changes character or hits the maximum prefix length.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), as it constructs the output string.
1function compressString(word) {
2 let result = '';
3 let start = 0;
4 while (start < word.length) {
5 let current = word[start];
6 let end = start;
7 while (end < word.length && word[end] === current && end - start < 9) {
8 end++;
9 }
10 let count = end - start;
11 result += count + current;
12 start = end;
13 }
14 return result;
15}
16
17console.log(compressString('abcde'));
18console.log(compressString('aaaaaaaaaaaaaabb'));
This JavaScript solution employs two indices to track the current character sequence as a window, appending results directly to a string variable.