Problem
/*
Given a array of characters of this replace the characters which occur continously with the character and no.
of times it occured e.g. AAAABCCDDD A4BC3D3 (count for characters that occurs once can be ignored). Do it Inplace.
*/
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Run length encoding
Created Date : 12-10-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
class RLE
{
public:
RLE(string& str){ _str = str; }
RLE(string&& str){ _str = str; }
RLE& Encode()
{
char *p1 = const_cast<char *>(_str.c_str());
char *p2 = p1;
char *pEnd = p1 + _str.size();
int cnt(0);
while(p2 < pEnd){
cnt ++;
if(*p2 != *(p2 + 1)){
*p1 ++ = *p2;
if(cnt != 1){
*p1 ++ = '0' + cnt;
}
cnt = 0;
}
p2 ++;
}
*p1 ++ = '\0';
return *this;
}
friend ostream& operator << (ostream& os, RLE& rle)
{
os << rle._str.c_str();
return os;
}
private:
string _str;
};
void DoTest(string str)
{
cout << "Input : " << str << endl;
RLE rle(str);
rle.Encode();
cout << "Output : " << rle << endl;
cout << "---------------------" << endl;
}
int main()
{
DoTest("AAAABCCDDD");
DoTest("ABCD");
DoTest("");
return 0;
}
Output
Input : AAAABCCDDD
Output : A4BC2D3
---------------------
Input : ABCD
Output : ABCD
---------------------
Input :
Output :
---------------------
Press any key to continue . . .
N.B
os << rle._str; is not correct, it will result in a wrong string