-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
1-6-string-compression.cpp
45 lines (42 loc) · 853 Bytes
/
1-6-string-compression.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
#include <iostream>
#include <string>
std::string compress(std::string str)
{
size_t original_length = str.length();
if (original_length < 2) {
return str;
}
std::string out{""};
int count = 1;
for( size_t i = 1; i < original_length; ++i ) {
if (str[i-1] == str[i]) {
++count;
} else {
out += str[i-1];
out += std::to_string(count);
count = 1;
}
if (out.length() >= original_length) {
return str;
}
}
out += str[original_length-1];
out += std::to_string(count);
if (out.length() >= original_length) {
return str;
}
return out;
}
int main()
{
std::string str, out;
std::cout << "Enter a string:\n";
std::cin >> str;
out = compress(str);
if (str.compare(out)) {
std::cout << str << " can be compressed to " << out << std::endl;
} else {
std::cout << str << " can not be compressed\n";
}
return 0;
}