0
点赞
收藏
分享

微信扫一扫

【LeetCode - 443】压缩字符串(模拟)

【LeetCode - 443】压缩字符串(模拟)_leetcode

【LeetCode - 443】压缩字符串(模拟)_leetcode_02

 

解题报告:

直接模拟。

class Solution {
public:
int compress(vector<char>& chars) {
int p = 0;
for(int i = 0; i<chars.size();) {
int j = i+1;
while(j<chars.size() && chars[j] == chars[i]) j++;
chars[p++] = chars[i];
if(j-i > 1) {
int cnt = j-i;
vector<int> tmp;//其中最多三个元素
while(cnt) {
tmp.push_back(cnt%10);
cnt /= 10;
} reverse(tmp.begin(), tmp.end());
for(int k = 0; k<tmp.size(); k++) chars[p++] = tmp[k]+'0';
}
i=j;
}
return p;
}
};


举报

相关推荐

0 条评论