0%

string-compression

String Compression – LeetCode 443

Problem

Description

Given an array of characters, compress it in-place.

The length after compression must always be smaller than or equal to the original array.

Every element of the array should be a character (not int) of length 1.

After you are done modifying the input array in-place, return the new length of the array.

Follow up:
Could you solve it using only O(1) extra space?

Answer

Original

Code

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
class Solution {
public:
int compress(vector<char>& chars) {
if(!chars.size()) return 0;
char c = ' ';
int cnt = 0;
auto wh = chars.begin();
for(auto ch = chars.begin(); ch != chars.end(); ++ch){
if(c == ' '){
c = *ch;
++cnt;
}else if(c != *ch){
*wh++ = c;
if(cnt != 1) {
for(auto &c: to_string(cnt))
*wh++ = c;
}
c = *ch;
cnt = 1;
}else{
++cnt;
}
}
*wh++ = c;
if(cnt != 1) {
for(auto &c: to_string(cnt))
*wh++ = c;
}
chars.erase(wh,chars.end());
return chars.size();
}
};

思路

简单的遍历后完成压缩。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$8$ ms,排名$72.79\%$

Better

思路

思路相同,写法更简洁。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$6$ ms,排名$72.73\%$

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int compress(vector<char>& chars) {
int lo=0;
int cnt=0;
for(int i=0; i<chars.size(); i++){
cnt++;
if(i==chars.size()-1||chars[i]!=chars[i+1]){
chars[lo++]=chars[i];
if(cnt>1){
string nums=to_string(cnt);
for(int i=0; i<nums.length(); i++){
chars[lo++]=nums[i];
}
}
cnt=0;
}
}
return lo;
}
};