-
Notifications
You must be signed in to change notification settings - Fork 0
/
Run-lengthEncoding.cpp
78 lines (65 loc) · 1.73 KB
/
Run-lengthEncoding.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
/*
This problem was asked by Amazon.
Run-length encoding is a fast and simple method of encoding strings.
The basic idea is to represent repeated successive characters as a single count and character.
For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
Implement run-length encoding and decoding.
You can assume the string to be encoded have no digits and consists solely of alphabetic characters.
You can assume the string to be decoded is valid.
#implementation
*/
#include<iostream>
#include<string>
using namespace std;
// encoding
string to_encoding(string s) {
int count = 1;
string result = "";
if (s.empty())
return s;
for(int i = 0; i < s.length() - 1; ++i) {
if (s[i] == s[i+1]) {
++count;
} else {
result += to_string(count) + string(1, s[i]);
count = 1;
}
}
// add the last element
result += to_string(count) + string(1, s[s.length() - 1]);
return result;
}
// sub-decoding : 4A -> AAAA
string sub_decoding(char c, int n) {
string result = "";
while(n){
result += string(1,c);
--n;
}
return result;
}
// decoding
string to_decoding(string s) {
string result = "";
int count = 0;
if (s.empty())
return s;
for(int i = 0; i < s.length(); ++i) {
if(isdigit(s[i])) {
count = count * 10 + stoi(string(1,s[i]));
}else {
result += sub_decoding(s[i], count);
count = 0;
}
}
return result;
}
//test
int main( int argc, char ** argv )
{
string s = "AAAABBBCCDAA";
cout << s << endl;
cout << to_encoding(s) << endl;
cout << to_decoding(to_encoding(s)) <<endl;
return 0;
}