-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCompression.cpp
More file actions
54 lines (44 loc) · 884 Bytes
/
StringCompression.cpp
File metadata and controls
54 lines (44 loc) · 884 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
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int compress(vector<char> &chars)
{
int n = chars.size();
int index = 0;
for (int i = 0; i < n; i++)
{
char ch = chars[i];
int count = 0;
while (i < n && chars[i] == ch)
{
count++;
i++;
}
if (count == 1)
{
chars[index] = ch;
index++;
}
else
{
chars[index] = ch;
index++;
string str = to_string(count);
for (char dig : str)
{
chars[index] = dig;
index++;
}
}
i--;
}
chars.resize(index);
return index;
}
int main()
{
vector<char> s = {'a', 'a', 'b', 'b', 'c', 'c', 'c'};
cout << compress(s) << endl;
return 0;
}