443.String Compression
443.String Compression
难度:Easy
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?
1
Example 1:
2
3
Input:
4
["a","a","b","b","c","c","c"]
5
6
Output:
7
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
8
9
Explanation:
10
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
11
12
13
Example 2:
14
15
Input:
16
["a"]
17
18
Output:
19
Return 1, and the first 1 characters of the input array should be: ["a"]
20
21
Explanation:
22
Nothing is replaced.
23
24
25
Example 3:
26
27
Input:
28
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
29
30
Output:
31
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
32
33
Explanation:
34
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
35
Notice each digit has it's own entry in the array.
36
37
38
Note:
39
40
All characters have an ASCII value in [35, 126].
41
1 <= len(chars) <= 1000.
Copied!
原地修改,需要注意重复元素出现次数,如果是1可以省略,后面补上的长度是次数的宽度。
1
class Solution {
2
public:
3
int compress(vector<char>& chars) {
4
int start=1;
5
int count=1;
6
int res=0;
7
for(int i=1;i<chars.size();i++)
8
{
9
if(chars[i]==chars[i-1])
10
count++;
11
else
12
{
13
if(count==1){
14
res+=1;
15
}
16
else
17
{
18
string tmp=to_string(count);
19
res+=1+tmp.length();
20
for(auto c:tmp)
21
chars[start++]=c;
22
count=1;
23
24
}
25
chars[start++]=chars[i];
26
}
27
}
28
29
if(count==1){
30
res+=1;
31
}
32
else
33
{
34
string tmp=to_string(count);
35
res+=1+tmp.length();
36
for(auto c:tmp)
37
chars[start++]=c;
38
}
39
return res;
40
}
41
};
Copied!
执行用时 :12 ms, 在所有 C++ 提交中击败了89.58%的用户 内存消耗 :9.1 MB, 在所有 C++ 提交中击败了91.06%的用户
Copy link