【leetcode】443. String Compression

本文详细解析了LeetCode第443题“字符串压缩”的算法解决方案,通过C++代码实现,介绍了如何在原地压缩字符数组,并返回压缩后的长度。示例包括对输入数组['a','a','b','b','c','c','c']和['a','a','a','b','b','a','a']的压缩过程。

problem

443. String Compression

Input
["a","a","b","b","c","c","c"]
Output
["a","a","b","b","c","c"]
Expected
["a","2","b","2","c","3"]

a:

Given an array of characters, compress it in-place.
After you are done modifying the input array in-place, return the new length of the array.

 

ss

Input
["a","a","a","b","b","a","a"]
Output
["a","5","b","2"]
Expected
["a","3","b","2","a","2"]

ss

solution1:

class Solution {
public:
    int compress(vector<char>& chars) {
        if(chars.empty()) return 0;
        string res="";
        char cur, pre;
        int num = 0;
        for(int i=0; i<chars.size(); i++)
        {
            cur = chars[i];
            if(i==0) 
            {
                res += cur;
                pre = cur;
            }
            
            if(cur!=pre)
            {
                if(num>1) res += to_string(num);//
                res += cur;
                pre = cur;
                num = 1;
            }
            else num++;
        }
        if(num>1) res += to_string(num);
        //
        int len = 0;
        if(res.size()> chars.size()) len = chars.size();
        else if(res.size()<=chars.size()) 
        {
            len = res.size();
            for(int i=0;i<res.size(); i++)
            {
                chars[i] = res[i];
            }
            
        }
        return len;
        
    }
};
View Code

 

 

 

 

参考

1. Leetcode_443. String Compression;

转载于:https://www.cnblogs.com/happyamyhope/p/10495914.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值