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 C solution uses an iterative approach where we count occurrences of each character up to a maximum of 9. We construct the result string manually.
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.