Repository navigation
Expand file tree
/
Copy path9_String Compression.cpp
More file actions
56 lines (54 loc) · 1.86 KB
/
Copy path9_String Compression.cpp
File metadata and controls
56 lines (54 loc) · 1.86 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
// 443. String Compression
// runtime:0 ms Beats 100.00%
// space : 14.06 MB Beats 10.70%
// O(1) extra space
// countstr 是一個字串(string),用於暫時儲存數字的字元表示。雖然它的大小可能會根據壓縮後的計數而變化,
// 但它在每次迭代後都會被重置,而且其最大長度是有限的(因為整數的位數是有限的)。因此,它也可以被視為使用常量空間。
class Solution {
public:
int compress(vector<char>& chars) {
int charsLen = chars.size();
char temp = chars[0];
int count = 0;
string countstr = "";
int resizenum = 0;
if(charsLen == 1){
chars[0] = temp;
return 1;
}
for(int i = 0;i<=charsLen;i++){
if(i == charsLen){
chars[resizenum] = temp;
resizenum++;
if(count > 1){
countstr = to_string(count);
for(int j = 0;j<countstr.size();j++){
chars[resizenum] = countstr[j];
resizenum++;
}
}
if(i<charsLen){
temp = chars[i];
count = 0;
}
}
else if(temp != chars[i]){ // 為了防止 i == charsLen 的時候訪問越界
chars[resizenum] = temp;
resizenum++;
if(count > 1){
countstr = to_string(count);
for(int j = 0;j<countstr.size();j++){
chars[resizenum] = countstr[j];
resizenum++;
}
}
if(i<charsLen){
temp = chars[i];
count = 0;
}
}
count++;
}
return resizenum;
}
};