-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
44 lines (33 loc) · 812 Bytes
/
main.cpp
File metadata and controls
44 lines (33 loc) · 812 Bytes
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
// main.cpp
#include <iostream>
#include <string>
std::string compress(std::string str);
int main() {
std::cout << compress("aaabbbbccdddz");
return 0;
}
std::string compress(std::string str) {
int counter = 0;
std::string result;
char lastCharacter = ' ';
for (char c: str) {
if (c != lastCharacter) {
if (counter > 0) {
result += lastCharacter;
result += std::to_string(counter);
}
lastCharacter = c;
counter = 1;
} else {
counter++;
}
}
if (counter > 0) {
result += lastCharacter;
result += std::to_string(counter);
}
if (result.size() > str.size()) {
result = str;
}
return result;
}