-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path443.string-compression.cpp
More file actions
64 lines (63 loc) · 1.5 KB
/
443.string-compression.cpp
File metadata and controls
64 lines (63 loc) · 1.5 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* @lc app=leetcode id=443 lang=cpp
*
* [443] String Compression
*/
// @lc code=start
#include <string>
using namespace std;
class Solution
{
public:
int compress(vector<char> &chars)
{
char cur = -1;
int group_length = 0;
int ptr = 0;
for (int i = 0; i < chars.size(); i++)
{
char c = chars[i];
if (group_length == 0 || cur == c)
{
group_length++;
}
else
{
// cur != c
chars[ptr++] = cur;
string num_str = "";
if (group_length > 1)
{
while (group_length)
{
num_str += group_length % 10 + '0';
group_length /= 10;
}
}
for (int j = num_str.length() - 1; j >= 0; j--)
{
chars[ptr++] = num_str[j];
}
group_length = 1;
}
cur = c;
}
// write last one
chars[ptr++] = cur;
string num_str = "";
if (group_length > 1)
{
while (group_length)
{
num_str += group_length % 10 + '0';
group_length /= 10;
}
}
for (int j = num_str.length() - 1; j >= 0; j--)
{
chars[ptr++] = num_str[j];
}
return ptr;
}
};
// @lc code=end