1.6 - String Compression
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).

Algorithm:

1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
5
6
char* strCompression(char* testStr){
7
8
int len = strlen(testStr);
9
int count = 1;
10
char* result = malloc((len + 1) * sizeof(char));;
11
result[0] = testStr[0];
12
13
int j = 1;
14
for(int i = 1; i < len; i++){
15
if(testStr[i - 1] == testStr[i]){
16
count++;
17
}else{
18
result[j] = count + '0';
19
result[j + 1] = testStr[i];
20
j += 2;
21
count = 1;
22
}
23
}
24
result[j] = count + '0';
25
return result;
26
}
Copied!

Test:

1
int main(){
2
char testStr[100] = "aakkkrleaarr";
3
printf("%s\n",testStr);
4
printf("Compression: %s\n", strCompression(testStr));
5
6
7
return 0;
8
}
Copied!
Copy link