Implement the function run_length_encode that accepts a string of
characters
as input and returns a compressed string of characters. The compression
process
should follow this recipe: if the character X appears more than once in a
row, replace all consecutive occurrences with a single instance of XN where
N is the count of occurrences and X is the character being repeated. For
example:
WWWABC should be replaced with W3ABC.
WWWWBBWWWWW should be replaced with W4B2W5.
Implement the function run_length_decode that accepts a compressed string
of
characters and returns it in its uncompressed form. Replace every instance
of
XN with the character X multiplied N times. For example:
W3ABC should be replaced with WWWABC.
W4B2W5 should be replaced with WWWWBBWWWWW.
Ensure that the following sentence is always valid:
str == run_length_decode(run_length_encode(str))
#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;
std::string run_length_decode(const std::string &str)
{
string des = str;
int i, j;
int strlen, timevalue;
char *value=NULL;
strlen = str.length();
i = j = timevalue = 0;
while(i < strlen)
{
while(des.at(i) >= '0' && des.at(i) <= '9' )
{
timevalue ++;
i++;
if(i >= strlen)
break;
}
if(timevalue > 0)
{
value = new char[timevalue+1];
// bzero(value, sizeof(char)*timevalue );
memset(value, 0x00, sizeof(char)*timevalue);
for(j=0; j<timevalue; j++)
{
value[j] = des.at(i-timevalue+j);
}
value[j] = '\0' ;
int va=atoi(value);
string tem;
tem.append(des, i, des.length() - i );
des.erase(i-timevalue, des.length() -i+ timevalue);
for(j=0; j<va-1; j++)
des.push_back(des[i-timevalue -1]) ;
des += tem;
timevalue = 0;
delete [] value;
}
i++;
strlen = des.length();
}
return des;
}
std::string run_length_encode(const std::string &str)
{
// Implement!
std::string des;
int strlen = str.length();
int i=0;
int time=0;
char a[64];
des = str;
while(i<strlen-1)
{
while(des.at(i)==des.at(i+1))
{
time ++;
i++;
if(i >= strlen-1)
break;
}
if(time>0)
{
time ++;
int tlen=snprintf(a, sizeof(a), "%d", time);
int relen = i-time+2;
des.replace(relen, tlen, a);
string tmp;
tmp.append(des, i+1 , des.length()-i);
des.erase(relen+tlen, des.length()-relen-tlen);
des += tmp;
i = i+2-time;
time = 0;
}
strlen = des.length();
i++;
}
//
return des;
}
int main()
{
string strTest="AAAAAADYUIOBBBBNLJJJHHHhhhhhhhhhhhhhhhhhhhhhHHHHHLKjjjjjjjjjjjF";
string des,ens;
des = run_length_encode(strTest);
ens = run_length_decode(des);
cout<<"res:"<<ens.compare(strTest)<<endl;
return 0;
}