Skip to content

Instantly share code, notes, and snippets.

@rep-movsd
Last active April 1, 2018 11:56
Show Gist options
  • Save rep-movsd/19608567b64dd403179bd5685fcfb610 to your computer and use it in GitHub Desktop.
Save rep-movsd/19608567b64dd403179bd5685fcfb610 to your computer and use it in GitHub Desktop.
// Always include C headers before C++ headers
#include <cctype>
#include <iostream>
#include <string>
// Use this with caution
using namespace std;
string compress(const string& sIn)
{
// We will use c_str() to ensure a NUL sentinel at the end
auto pszIn = sIn.c_str();
string sRet;
while(*pszIn)
{
if(!isalpha(*pszIn))
{
throw runtime_error("Invalid String");
}
// There is always at least 1 count
int c = 1;
// Keep skipping forward as long as the current and next match, since we have a NUL as a sentinel, we dont bother about EOS
while(*pszIn == pszIn[1])
{
++c;
++pszIn;
}
// Append the character and count;
sRet += *pszIn;
sRet += to_string(c);
// Jump to next group
++pszIn;
}
if(sRet.size() > sIn.size())
{
throw runtime_error("Cannot compress");
}
return sRet;
}
const string g_sTest[] =
{
"aaabccdefgggg",
"abcdef",
"aaaaaabbbbacde",
"azzzxaaacccddddeef"
};
int main()
{
for(const auto &s: g_sTest)
{
cout << s << ": " << compress(s) << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment