问题描述
解题思路
双指针、滑动窗口,注意for
循环中不需要fast++
。
代码
class Solution {
public:
int compress(vector<char>& chars) {
vector<char> res;
int cnt = 0;
for (int slow = 0, fast = 0; fast < chars.size(); ) {
while (fast < chars.size() && chars[fast] == chars[slow])
fast++;
cnt = fast - slow;
if (cnt == 1)
res.push_back(chars[slow]);
else if (cnt > 1 && cnt <= 9) {
res.push_back(chars[slow]);
res.push_back(cnt + '0');
} else if (cnt >= 10 && cnt <= 99) {
res.push_back(chars[slow]);
res.push_back(cnt / 10 + '0');
res.push_back(cnt % 10 + '0');
} else if (cnt >= 100 && cnt <= 999) {
res.push_back(chars[slow]);
res.push_back(cnt / 100 + '0');
res.push_back((cnt % 100) / 10 + '0');
res.push_back((cnt % 100) % 10 + '0');
} else {
res.push_back(chars[slow]);
res.push_back(cnt / 1000 + '0');
res.push_back((cnt % 1000) / 100 + '0');
res.push_back((cnt % 1000) % 100 / 10 + '0');
res.push_back(cnt % 1000 % 100 % 10 + '0');
}
slow = fast;
}
chars = res;
return res.size();
}
};
标签:cnt,slow,443,压缩,fast,int,&&,字符串,chars
From: https://www.cnblogs.com/zwyyy456/p/17478089.html