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;
}