[leetcode]443. String Compression

本文详细介绍了LeetCode上第443题“字符串压缩”的解决方案。通过一个简单的C++实现,文章展示了如何在原地压缩字符数组,并提供了完整的代码示例。该方法适用于需要在有限空间内进行高效字符串压缩的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[leetcode]443. String Compression


Analysis

everyday is the first day of your rest life—— [间歇性迷茫+2~]

Given an array of characters, compress it in-place.
压缩字符串,基本上看样例就能明白意思了。

Implement

class Solution {
public:
    int compress(vector<char>& chars) {
        if(chars.size() == 0)
            return 0;
        int len = chars.size();
        int cnt = 1;
        int res = 1;
        char t = chars[0];
        for(int i=1; i<len; i++){
            if(chars[i] == t)
                cnt++;
            else{
                if(cnt > 1){
                    string s = to_string(cnt);
                    for(auto c:s)
                        chars[res++] = c;
                }
                cnt = 1;
                t = chars[i];
                chars[res++] = t;
            }
        }
        if(cnt > 1){
            string s = to_string(cnt);
            for(auto c:s)
                chars[res++] = c;
        }
        chars.resize(res);
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值