forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path443_String_Compression.c++
More file actions
44 lines (42 loc) · 1.07 KB
/
443_String_Compression.c++
File metadata and controls
44 lines (42 loc) · 1.07 KB
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
// Name :String Compression
// Url: https://leetcode.com/problems/string-compression/
// Tag : String
class Solution
{
public:
int compress(vector<char> &chars)
{
char temp = chars[0];
int cnt = 0, n = chars.size();
for (int i = 0; i < n; i++)
{
if (chars[i] == temp)
cnt++;
else
{
chars.erase(chars.begin(), chars.begin() + i);
i = 0;
n -= cnt;
chars.push_back(temp);
if (cnt != 1)
{
string k = to_string(cnt);
for (auto x : k)
chars.push_back(x);
}
temp = chars[i];
cnt = 1;
continue;
}
}
chars.erase(chars.begin(), chars.begin() + cnt);
chars.push_back(temp);
if (cnt != 1)
{
string k = to_string(cnt);
for (auto x : k)
chars.push_back(x);
}
return chars.size();
}
};