Skip to content

Instantly share code, notes, and snippets.

@marchelbling
Created August 17, 2012 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marchelbling/3378178 to your computer and use it in GitHub Desktop.
Save marchelbling/3378178 to your computer and use it in GitHub Desktop.
simple string compressor
//examples:
// compress("AABBBCCCCCAADDDD") == "2A3B5C2A4D"
// compress("PPPQRRRSTTQQS") == "3PQ3RS2T2QS"
// compress("uvw") == "uvw"
#include<sstream>
#include<string>
void _format(std::ostringstream& out, size_t counter, char current)
{
if(counter == 1)
out << current;
else
out << counter << current;
}
std::string compress(std::string const& input)
{
if(input.size() == 0)
return std::string();
std::ostringstream out;
size_t counter = 0;
char current = input[0];
for(std::string::const_iterator it_char = input.begin(); it_char != input.end(); ++ it_char)
{
if(*it_char == current)
++ counter;
else
{
_format(out, counter, current);
current = *it_char;
counter = 1;
}
}
_format(out, counter, current);
return out.str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment