Skip to content

Instantly share code, notes, and snippets.

@rep-movsd
Created April 1, 2018 18:04
Show Gist options
  • Save rep-movsd/2eb9ddb0677939f37eb256e32aaa0f81 to your computer and use it in GitHub Desktop.
Save rep-movsd/2eb9ddb0677939f37eb256e32aaa0f81 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;
for(size_t i = 0; pszIn[i];)
{
if(!isalpha(pszIn[i]))
{
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[i + c - 1] == pszIn[i + c])
{
++c;
}
// Append the character and count;
sRet += pszIn[i] + to_string(c);
// Jump to next group
i += c;
}
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