forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths1.cpp
More file actions
26 lines (26 loc) · 725 Bytes
/
s1.cpp
File metadata and controls
26 lines (26 loc) · 725 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
// OJ: https://leetcode.com/problems/string-compression/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int compress(vector<char>& chars) {
int i = 0, N = chars.size(), j = 0, r = 0;
while (i < N) {
j = i + 1;
while (j < N && chars[j] == chars[i]) ++j;
chars[r++] = chars[i];
if (j - i > 1) {
int cnt = j - i, pow = 1;
while (cnt / (pow * 10)) pow *= 10;
while (pow) {
chars[r++] = '0' + cnt / pow;
cnt %= pow;
pow /= 10;
}
}
i = j;
}
return r;
}
};