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:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char* strCompression(char* testStr){
    
    int len = strlen(testStr);
    int count = 1;
    char* result = malloc((len + 1) * sizeof(char));;
    result[0] = testStr[0];
    
    int j = 1;
    for(int i = 1; i < len; i++){
        if(testStr[i - 1] == testStr[i]){
            count++;
        }else{
            result[j] = count + '0';
            result[j + 1] = testStr[i];
            j += 2;
            count = 1;
        }
    }
    result[j] = count + '0';
    return result;
}

Test:

int main(){
    char testStr[100] = "aakkkrleaarr";
    printf("%s\n",testStr);
    printf("Compression: %s\n", strCompression(testStr));
    

    return 0;
}

Last updated