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.
1public class StringCompressor {
2 public static String compressString(String word) {
3 StringBuilder result = new StringBuilder();
4 int start = 0;
5 while (start < word.length()) {
6 char current = word.charAt(start);
7 int end = start;
8 while (end < word.length() && word.charAt(end) == current && end - start < 9) {
9 end++;
10 }
11 int count = end - start;
12 result.append(count).append(current);
13 start = end;
14 }
15 return result.toString();
16 }
17
18 public static void main(String[] args) {
19 System.out.println(compressString("abcde"));
20 System.out.println(compressString("aaaaaaaaaaaaaabb"));
21 }
22}
In this Java solution, start
and end
form a window to capture sequences of identical characters, capturing counts and storing them efficiently in a StringBuilder
.