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.
1using System;
2
3class StringCompressor {
4 public static string CompressString(string word) {
5 System.Text.StringBuilder result = new System.Text.StringBuilder();
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.Append(count).Append(current);
15 start = end;
16 }
17 return result.ToString();
18 }
19
20 public static void Main(string[] args) {
21 Console.WriteLine(CompressString("abcde"));
22 Console.WriteLine(CompressString("aaaaaaaaaaaaaabb"));
23 }
24}
This C# solution uses a sliding window model with start
and end
indexes to identify repetitious blocks of characters and build their respective outputs with a StringBuilder
.