Question

String compression

Using the counts of repeated characters

aabcccccaaa -> a2b1c5a3

Image uploaded from iOS (2).jpg


char* compression(const char* input, char *output) {
    int len = strlen(input);
    char prev = '\0';
    int read = 0;
    int write = 0;
    int count = 0;
    while (read < len && write < (len - 1)) {
         if (input[read] != prev) {
             if (count > 0) {
                output[write++] = '0' + count;
            }
            output[write++] = input[read];
            prev = input[read];
            count = 1;
        }
        else {
            count++;
        }
        read++;
    }

    if (write < (len - 1)) {
        output[write++] = '0' + count;
        output[write] = 0;
    }
    else {
        memcpy(output, input, strlen(input) + 1);
    }
    return output;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s