-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRLE.cpp
82 lines (62 loc) · 1.43 KB
/
RLE.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<iostream>
#include<fstream>
#include <sstream>
#include <string>
#include<cstdlib>
#include "rle.h"
/** Call Implementation
RLE rle(text);
cout<<"\nEncoded String : "<<endl;
string encoded_text=rle.encode();
cout<<"\n\nDecoded String : "<<endl;
rle.decode(encoded_text);
**/
using namespace std;
namespace patch
{
template < typename T > std::string to_string( const T& n )
{
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
RLE :: RLE(string raw_string){
text=raw_string;
}
string RLE :: encode(){
stringstream ss;
string newString="";
char currentLetter=text[0];
int letterNum=1,i=1, len=text.length();
while(i<=len){
if(text[i]==currentLetter){
letterNum++;
i++;
}
else{
while(letterNum>9){
newString+=currentLetter+patch::to_string(9);
letterNum-=9;
}
newString+=currentLetter+patch::to_string(letterNum);
currentLetter=text[i];
letterNum=1;
i++;
}
}
cout<<newString;
return newString;
}
void RLE :: decode(string text){
string decodedText="";
int index=0,len=text.length(),freq;
while(index<len){
freq=text[index+1]-48;
for(int i=0;i<freq;i++){
decodedText+=text[index];
}
index+=2;
}
cout<<decodedText;
}