-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringCompression.cpp
63 lines (50 loc) · 1.17 KB
/
StringCompression.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
#include <iostream>
#include <string>
using namespace std;
/*
Enter a string: abbbcbb
abbbcbb can't be compress
Enter a string: hhhrer
hhhrer can't be compress
Enter a string: aaadddddddbbbbc
aaadddddddbbbbc can be compressed to a3d7b4c1
Enter a string: abbbb
abbbb can be compressed to a1b4
*/
string copmress(string str)
{
int originL = str.length();
if (originL < 2)
return str;
string out("");
int count = 1;
for (int i = 1; i < originL; i++)
{
if (str[i - 1] == str[i])
count++;
else
{
out += str[i - 1];
out += to_string(count);
count = 1;
}
if (out.length() >= originL)
return str;
}
out += str[originL - 1];
out += to_string(count);
if (out.length() >= originL)
return str;
return out;
}
int main(void)
{
string str, out;
cout << "\nEnter a string: ";
cin >> str;
out = copmress(str);
if (str.compare(out))
cout << str << " can be compressed to " << out << endl;
else
cout << str << " can't be compress" << endl;
}