从Leetcode 每日一题练习继续讨论:
3163. 压缩字符串 III
3163. String Compression III
题解
本题读懂题意后其实并不难,就是一个单纯的字符串统计,从头遍历字符串,统计当前重复出现的字符个数,当个数达到9个时或者遇到新字符时就向comp字符串末尾添加当前重复字符的重复次数和字符本身。
代码
class Solution {
public:
string compressedString(string word) {
char num = '0';
char current = word[0];
string result;
for(auto ch:word){
if (ch == current){
if (num == '9'){
result.push_back(num);
result.push_back(current);
num = '1';
continue;
}
num++;
}else if(ch != current){
result.push_back(num);
result.push_back(current);
num = '1';
current = ch;
}
}
result.push_back(num);
result.push_back(current);
return result;
}
};