443. String Compression

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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.

这里写图片描述

2,题目思路
遍历整个字符数组即可,可以重新创建一个字符数组来记录,这样比较明了。不过若是想要在O(1)的空间内完成,就直接在原字符串数组上进行操作即可。
值得注意的一点是,如何将一个整数化成单个单个的字符形式。一开始想了一些办法,但是都不好。
最好的办法是利用to_string( )将数字转化为字符串,然后再用for(char c : str)方法获得整个字符串中的单个单个的字符。

3,程序源码

class Solution {
public:
    int compress(vector<char>& chars) {
        vector<char> res;
        int charPos = 0;
        for(int i = 0;i<chars.size();i++)
        {
            if((i+1) == chars.size() || chars[i]!=chars[i+1])
            {
                res.push_back(chars[i]);  //将对应的字符添加到res中
                if(i-charPos>=1)   //出现次数超过一次
                {
                    string tmp = to_string(i-charPos+1);
                    for(char c : tmp)
                        res.push_back(c);
                }
                charPos = i+1;
            }            
        }
        chars = res;
        return (int)res.size();
    }
};    

利用O(1)空间操作:

class Solution {
public:
    int compress(vector<char>& a) {
        int i = 0, t = 0;
        for (int j = 0; j < a.size(); ++j)  //遍历
            if (j+1 == a.size() || a[j+1] != a[j]) {    //到达结尾或者发现不同的元素
                a[t++] = a[j];  //记录下当前的字母,然后t++
                if (j >= i + 1) {   //字母出现的次数超过1次,就记录下来
                    string s = to_string(j-i+1);    //将出现的次数转化为字符串的形式,然后按char写入到原字符数组中
                    for (char c:s) a[t++] = c;
                }
                i = j + 1;
            }
        return t;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值