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 Python solution uses a list to build the result string efficiently, iterating through the input with nested loops to count 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.
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.