443. String Compression

Given an array of characters, compress it in-place.

The length after compression must always be smaller than or equal to the original array.

Every element of the array should be a character (not int) of length 1.

After you are done modifying the input array in-place, return the new length of the array.


Follow up:
Could you solve it using only O(1) extra space?


Example 1:

Input:
["a","a","b","b","c","c","c"]

Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".

该题要compress in-place

意味着不能做出新数组,那么要多的步骤是,压缩过程会不会有可能覆盖还没压缩的字母,最后要把多的部分删除。

第一个是字母,第二个跟数字,可知数字长度不会长于字母个数长度,因此第一个问题不会覆盖。

那么细节比较多,如要设置一个当前压缩后的位置,遍历数组的同时,不断压缩进去,压缩后的位置pre也要移动。还要增加判断条件字母个数为一个和多于一个的时候。

压缩的判断条件是,遍历数组的时候直到遇到非当前的字母。


class Solution {
public:
    int compress(vector<char>& chars) {
        int temp = chars[0];
        int pre=0;
        int size = chars.size();
        int k = 1;
        for(int i=1;i<size;i++){
            if(chars[i]==temp) k++;
            if(chars[i]!=temp){
                chars[pre] = temp;
                if(k>1){
                    string s = to_string(k);
                    for(int j=0;j<s.size();j++, pre++) chars[pre+1]=s[j];
                    pre++;
                }else{
                    pre++;
                }
                k=1;
                temp=chars[i];
            }
        }
        chars[pre] = temp;
        if(k>1){
            string s = to_string(k);
            for(int j=0;j<s.size();j++, pre++) chars[pre+1]=s[j];
        }
        for(int i=pre+1;i<size;i++){
            chars.pop_back();
        }
        return chars.size();
    }
};



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值