-
Notifications
You must be signed in to change notification settings - Fork 0
/
dailycoding029.cpp
55 lines (41 loc) · 974 Bytes
/
dailycoding029.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
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using std::map;
using std::cout;
using std::endl;
using std::string;
string runLengthEncode(string str) {
int i, j, count;
string result = "";
i = j = count = 0;
if (str == "") return "";
// use two pointers for keeping count to create the encoding
while (j < str.length()) {
if (str[i] == str[j]) {
j++;
count++;
} else {
result += (std::to_string(count) + str[i]);
count = 0;
i = j;
}
}
return result + (std::to_string(count) + str[i]);
}
bool testHandle() {
map<string, string> tests;
tests["AAAABBBCCDAA"] = "4A3B2C1D2A";
tests["AAAAAAAA"] = "8A";
tests["abcdef"] = "1a1b1c1d1e1f";
for (auto const& pair: tests) {
if (runLengthEncode(pair.first) != pair.second) return false;
}
return true;
}
int main() {
if (testHandle()) cout << "Passed" << endl;
else cout << "Failed" << endl;
return 0;
}