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.
1def compress_string(word):
2 result = []
3 start = 0
4 while start < len(word):
5 current = word[start]
6 end = start
7 while end < len(word) and word[end] == current and end - start < 9:
8 end += 1
9 count = end - start
10 result.append(f'{count}{current}')
11 start = end
12 return ''.join(result)
13
14print(compress_string('abcde'))
15print(compress_string('aaaaaaaaaaaaaabb'))
This Python solution uses a two-pointer technique to count and store sequences of repeated characters in the word
string, appending results to a list and joining them at the end.