CTCI: Ch. 1-5

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.

#include <iostream>
#include <math.h>
using namespace std;
int coutCompression(char *inputStr);
string compressStr(char *inputStr);

string compressStr(char *inputStr)
{
    int compressSize = coutCompression(inputStr);
    if(compressSize >= strlen(inputStr))
    {
        return inputStr;
    }
    else
    {
        int count = 1;
        char last = inputStr[0];
        string newStr = "";
        
        for(int i=1;i<strlen(inputStr);i++)
        {
            if(inputStr[i] == last)
            {
                count++;
            }
            else
            {
                // string (size_t n, char c);
                newStr += string(1,last) + to_string(count);
                last = inputStr[i];
                count = 1;
            }
        }
        newStr += string(1,last) + to_string(count);
        return newStr;
    }
    
}

int coutCompression(char *inputStr)
{
    int size = 0;
    int count = 1;
    char last = inputStr[0];

    for(int i=1;i<strlen(inputStr);i++)
    {
        if(inputStr[i] == last)
        {
            count++;
        }
        else
        {
            last = inputStr[i];
            size += 1 + (floor(log10(abs(count))) + 1);
            /*
                Find the length of an integer:
                    if count != 0, digits = floor(log10(abs(count))) + 1
                    if count = 0, digits = 1
             */
            count = 1;
        }
    }
    size += 1 + (floor(log10(abs(count))) + 1); //count the last char, for example, last="aaa" in this case
    
    return size;
}

int main(int argc, const char * argv[])
{
    char inputStr[] = "aabcccccaaa";
    cout<<compressStr(inputStr)<<endl;
    
    return 0;
}

 

Leave a Reply