Leetcode 443 String Compression
题目原文
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".Note:
- All characters have an ASCII value in
[35, 126]
.1 <= len(chars) <= 1000
题意分析
压缩字符数组,如果某字符连续出现一次,则不进行任何操作,如果连续出现两次以上,则保留第一个字符,下一个字符用出现次数表示,如出现次数大于9,则用多位字符表示。求最后得到的vector的长度。要求额外的空间消耗小于n。
解法分析
为了避免额外的内存消耗,考虑在原有vector上进行操作。对重复出现次数进行转化为vector操作,然后插入删除重复元素后的原vector中。为了使得到vector末端进行的操作和中间一样,可以在chars末尾加入一个和前面字符都不同的字符,最后将其pop。C++代码如下:
class Solution {
public:
vector<char> toVector(int k){//important
stringstream ss;
string myString;
vector<char> res;
ss<<k;
ss>>myString;
res.assign(myString.begin(),myString.end());
return res;
}
int compress(vector<char>& chars) {
int count=1;
int n=chars.size();
if(n==1||n==0)
return n;
vector<char> number;
int start=0;
int i;
chars.push_back(33);
for(i=1;i<chars.size();i++){
if(chars[i]==chars[i-1])
count++;
else{
if(count==1){
start=i;//the start should be changed
continue;
}
number=toVector(count);
chars.erase(chars.begin()+start+1,chars.begin()+i);
i-=count-1;
count=1;
chars.insert(chars.begin()+i,number.begin(),number.end());
i+=number.size();
start=i;
}
}
chars.pop_back();
n=chars.size();
return n;
}
};
需要注意当出现不同字符且count仍为1时,不需进行插入操作,但start需要更新。int转vector可以先利用stringstream将int转化为string,再利用顺序容器的assign操作,将string赋值给一个vector,assign函数用于给不同类但元素类型相同的顺序容器相互赋值。