-
Notifications
You must be signed in to change notification settings - Fork 0
/
#29.cpp
59 lines (49 loc) · 992 Bytes
/
#29.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
#include <iostream>
#include <string>
#include <assert.h>
#include <ctype.h>
using namespace std;
string runLengthEncoding(string s) {
char curr = '\0';
int count = 0;
string output = "";
for (char c : s) {
if (c == curr) {
count++;
} else {
if (count != 0) output = output + to_string(count) + curr;
curr = c;
count = 1;
}
}
output = output + to_string(count) + curr;
return output;
}
string runLengthDecoding(string s) {
assert(s.size() % 2 == 0);
string output = "";
for (int i = 0; i < s.size(); i+=2) {
int count = s[i] - '0';
char curr = s[i+1];
for (int j = 0; j < count; j++) {
output += curr;
}
}
return output;
}
bool hasDigit(string s) {
for (char c : s) {
if (isdigit(c)) return true;
}
return false;
}
int main() {
string inp;
while (cin >> inp) {
if (hasDigit(inp)) {
cout << "Decoded Result: " << runLengthDecoding(inp) << endl;
} else {
cout << "Encoded Result: " << runLengthEncoding(inp) << endl;
}
}
}