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?
Example 1
Input:
["a","a","b","b","c","c","c"]
Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
Example 2
Input:
["a"]
Output:
Return 1, and the first 1 characters of the input array should be: ["a"]
Explanation:
Nothing is replaced.
Example 3
Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.
Note
1.All characters have an ASCII value in [35, 126].
2.1 <= len(chars) <= 1000.
Solution 1(C++)
class Solution {
public:
int compress(vector<char>& ch) {
int w=0;
for (int i=0,j=0; i<ch.size(); i=j){
for (j=i; j<ch.size() && ch[i]==ch[j]; ++j){}
ch[w++]=ch[i];
if (j-i>1)
for (auto c: to_string(j-i))
ch[w++]=c;
}
return w;
}
};
Solution 2(C++)
class Solution {
public:
int compress(vector<char>& chars) {
int index=0;
for(int i=0, j=0; j<chars.size(); i=j){
while(j<chars.size() && chars[i]==chars[j]) j++;
chars[index++]=chars[i];
if(j-i>1){
for(auto c: to_string(j-i)){
chars[index++]=c;
}
}
}
return index;
}
};
算法分析
像这种问题啊,第一步就是要明白题目的意思,然后要能将算法流程转换为代码,这是很关键的,说白了,就是如何组织代码结构,并且选择合适的API函数,来帮助自己高效的完成代码开发。比如说,这里的to_string()函数,用的就很精髓,非常简单高效。将j-1转换成字符串,然后遍历其中每一个字符,从前往后。比做除法、取模、结果转换成字符、调用insert()函数高效多了。而且,运算的速度也不慢。所以,这样的代码就很值得学习。
程序分析
如上所说,这种代码可以多写几遍。
后来更新解法二,解法二是我自己写的,其实自己写一遍才能真正明白其中难点。我个人觉得难点就是那个循环,一般要i=j,但是,我在for循环中额外加了一个j++,这就导致程序不能正常运行,其实找一个例子,仔细分析一下,可以不需要这个j++。因为不要j++之后,循环结束必然i=j,那么循环中第一句一定能执行,那么这样,j++就通过这种形式完成了。