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
This Java solution leverages a StringBuilder
for efficient string construction, iterating through the input to count consecutive characters.
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.
1#include <iostream>
2#include <string>
3
4std::string compressString(const std::string& word) {
5 std::string result;
6 int start = 0;
7 while (start < word.length()) {
8 char current = word[start];
9 int end = start;
10 while (end < word.length() && word[end] == current && end - start < 9) {
11 ++end;
12 }
13 int count = end - start;
14 result += std::to_string(count) + current;
15 start = end;
16 }
17 return result;
18}
19
20int main() {
21 std::cout << compressString("abcde") << std::endl;
22 std::cout << compressString("aaaaaaaaaaaaaabb") << std::endl;
23 return 0;
24}
This C++ solution implements a window with two pointers start
and end
to find sequences of the same character, appending to the result when different characters are found.