HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Run Length Encoding

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lengthrunencoding

Problem

Given an input string, write a function that returns the Run Length
Encoded string for the input string.


For example, if the input string is “wwwwaaadexxxxxx”, then the
function should return “w4a3d1e1x6″.

The following is my implementation:

string length_encoding(const string& s)
{
    char c = ' ';
    int num = 0;
    string result;
    string::const_iterator it = s.begin();
    for(; it != s.end(); ++it)
    {
        if(*it!=c)
        {
            if(num!=0)
            {
                stringstream ss;
                ss << num;
                string num_s(ss.str());
                result += num_s;
            }

            c = *it;
            result.push_back(c);

            num = 1;
        }
        else
        {
            num++;
        }       
    }

    stringstream ss;
    ss << num;
    string num_s(ss.str()); 
    result += num_s;

    return result;
}

Solution

There is a bug. If your input string begins with a space then you don't prefix the number with a space.

Input:           "    AAAA"
Output:          "4A4"
Expected Output: " 4A4"


This is easily fixed by outputting the character and count at the same time.

Problems: Magic values

char c = ' ';


Magic values cause all sorts of problems you should really use a value that can never be a character. In this case convert to an int and make it -1

int c = -1; // This is guaranteed to be a value that will never be a character.


Use the ability to declare variables inside the for(;;) statement unless you really need the iterator after the loop.

string::const_iterator it = s.begin();
for(; it != s.end(); ++it)

// easier to write and read as:

for(string::const_iterator it = s.begin(); it != s.end(); ++it) 
{
    // Also because `it` is scopped is does not pollute the
    // code with a variable that is not used after the loop.
}


This piece of code:

stringstream ss;
            ss << num;
            string num_s(ss.str());
            result += num_s;


Is repeated in two places. Refactor it into its own function.

You will also find that such a function already exists in boost std::lexical_cast

Code Snippets

Input:           "    AAAA"
Output:          "4A4"
Expected Output: " 4A4"
char c = ' ';
int c = -1; // This is guaranteed to be a value that will never be a character.
string::const_iterator it = s.begin();
for(; it != s.end(); ++it)

// easier to write and read as:

for(string::const_iterator it = s.begin(); it != s.end(); ++it) 
{
    // Also because `it` is scopped is does not pollute the
    // code with a variable that is not used after the loop.
}
stringstream ss;
            ss << num;
            string num_s(ss.str());
            result += num_s;

Context

StackExchange Code Review Q#19990, answer score: 6

Revisions (0)

No revisions yet.