下面反向遍历,还是正向好。
void left(vector<char>& v, bool p(int)) {
int max_index = v.size() - ; int del = -;
int rel = -;
while (del < max_index) {
while (p(v[del]) && del < max_index)
del++;
if (del >= max_index)
break;
if (rel < del)
rel = del;
while (!p(v[rel]) && rel <= max_index)
rel++;
if (rel > max_index)
break;
swap(v[del], v[rel]);
del++;
}
} int compress(vector<char>& chars) {
int size = chars.size();
int point = size - ;
int count = ;
for (int i = point; i >= ; i--) {
if (chars[i] == chars[i - ] && i > )
count++;
else if (count > ) {
for (int j = count - ; j > ; j--)
chars[i + j] = ;
string temp = to_string(count);
for (int j = ; j < temp.size(); j++)
chars[i + j + ] = temp[j];
count = ;
}
}
left(chars, [](int v) {return v != ;});
return count_if(chars.begin(), chars.end(), [](int v) {return v != ;});
}
其他答案:
int compress(vector<char>& chars) {
int lo=;
int cnt=;
for(int i=; i<chars.size(); i++){
cnt++;
if(i==chars.size()-||chars[i]!=chars[i+]){
chars[lo++]=chars[i];
if(cnt>){
string nums=to_string(cnt);
for(int i=; i<nums.length(); i++){
chars[lo++]=nums[i];
}
}
cnt=;
}
}
return lo;
}