LeetCode第 443 题:压缩字符串(C++)

443. 压缩字符串 - 力扣(LeetCode)
在这里插入图片描述
从左到右进行读取。当读到最后一个字符,或者下一个下一个字符与当前不同时,则到达连续区块的结尾。

当我们到达连续区块的结尾时,就从写入压缩的结果,过程总需要记录字符与个数。

class Solution {
public:
    int compress(vector<char>& chars) {
        int n = chars.size(), len = 0;//len用来标记我们的下一个写入位置下标
        int cnt = 1; //计数器
        for(int i = 0; i < n; ++i){
            if(i == n-1 || chars[i] != chars[i+1]){//最后一个元素的时候直接处理
                chars[len++] = chars[i];
                string s = to_string(cnt);
                if(cnt > 1){
                    for(const auto &c : s)  chars[len++] = c;
                }
                cnt = 1;//重置计数器
            }else ++cnt;//累加计数器
        }
        return len;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32523711/article/details/109106406