[leetcode]443. String Compression
Analysis
everyday is the first day of your rest life—— [间歇性迷茫+2~]
Given an array of characters, compress it in-place.
压缩字符串,基本上看样例就能明白意思了。
Implement
class Solution {
public:
int compress(vector<char>& chars) {
if(chars.size() == 0)
return 0;
int len = chars.size();
int cnt = 1;
int res = 1;
char t = chars[0];
for(int i=1; i<len; i++){
if(chars[i] == t)
cnt++;
else{
if(cnt > 1){
string s = to_string(cnt);
for(auto c:s)
chars[res++] = c;
}
cnt = 1;
t = chars[i];
chars[res++] = t;
}
}
if(cnt > 1){
string s = to_string(cnt);
for(auto c:s)
chars[res++] = c;
}
chars.resize(res);
return res;
}
};