About Me

My photo
Mostly software programming related blogs.

Thursday, October 25, 2012

Compress String


/* compress the string for example aabbbcccccdeff should become a2b3c5d1e1f2
 * if compress string length remain same as original string then return
 * original string */

using namespace std;

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

main() {

        string input;
        cout << " enter input string to be compressed: ";
        cin >> input;

        string::size_type len = input.size();

        string::size_type orig_len = len;

        string::size_type i = 0;

        int sameCharCount = 1;

        bool in_progress = false;

        char buf[10];

        while (i < len) {
   
                if (input[i] == input[i+1]) {
                        in_progress = true;
                        sameCharCount++;
                } else if (in_progress) {
                        in_progress = false;
                        sprintf(buf, "%d", sameCharCount);
                        input.replace(i-sameCharCount+2, sameCharCount-1, buf);
                        len = len - sameCharCount + 1 + strlen(buf);
                        i = i - sameCharCount + 1 + strlen(buf);
                        sameCharCount = 1;

                } else {
                        input.insert(i+1, "1");
                        i++;
                        len++;
                }
                i = i + 1;
        }

        if (input.size() < orig_len) {
                cout << "changed string: " << input << endl;
        } else {
                cout << "string was not compressed" << endl;
        }
}
$ ./a.out 
 enter input string to be compressed: aaabb
changed string: a3b2
$ ./a.out 
 enter input string to be compressed: ab
string was not compressed
$ ./a.out 
 enter input string to be compressed: acc
string was not compressed
$ ./a.out 
 enter input string to be compressed: b
string was not compressed
$ ./a.out 
 enter input string to be compressed: bc
string was not compressed
$ ./a.out 
 enter input string to be compressed: abc
string was not compressed
$ ./a.out 
 enter input string to be compressed: aaabbbbbbbbbbbbddddddddddd
changed string: a3b12d11

No comments: