Leetcode算法学习日志-443 String Compression

Leetcode 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".

Note:

  1. All characters have an ASCII value in [35, 126].
  2. 1 <= len(chars) <= 1000

题意分析

压缩字符数组,如果某字符连续出现一次,则不进行任何操作,如果连续出现两次以上,则保留第一个字符,下一个字符用出现次数表示,如出现次数大于9,则用多位字符表示。求最后得到的vector的长度。要求额外的空间消耗小于n。

解法分析

为了避免额外的内存消耗,考虑在原有vector上进行操作。对重复出现次数进行转化为vector操作,然后插入删除重复元素后的原vector中。为了使得到vector末端进行的操作和中间一样,可以在chars末尾加入一个和前面字符都不同的字符,最后将其pop。C++代码如下:

class Solution {
public:
    vector<char> toVector(int k){//important
        stringstream ss;
        string myString;
        vector<char> res;
        ss<<k;
        ss>>myString;
        res.assign(myString.begin(),myString.end());
        return res;    
    }
    int compress(vector<char>& chars) {
        int count=1;
        int n=chars.size();
        if(n==1||n==0)
            return n;
        vector<char> number;
        int start=0;
        int i;
        chars.push_back(33);
        for(i=1;i<chars.size();i++){
            if(chars[i]==chars[i-1])
                count++;
            else{
                if(count==1){
                    start=i;//the start should be changed
                    continue;     
                }
                number=toVector(count);
                chars.erase(chars.begin()+start+1,chars.begin()+i);
                i-=count-1;
                count=1;
                chars.insert(chars.begin()+i,number.begin(),number.end());
                i+=number.size();
                start=i;
            }
        }
        chars.pop_back();
        n=chars.size();
        return n;
    }
};
需要注意当出现不同字符且count仍为1时,不需进行插入操作,但start需要更新。int转vector可以先利用stringstream将int转化为string,再利用顺序容器的assign操作,将string赋值给一个vector,assign函数用于给不同类但元素类型相同的顺序容器相互赋值。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值