443. String Compression

来源:互联网 发布:淘宝抢购秒杀要刷新吗 编辑:程序博客网 时间:2024/06/01 08:22

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();    }};



原创粉丝点击