【leetcode】443. String Compression

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;

posted on 2019-03-08 15:02  鹅要长大  阅读(214)  评论(0编辑  收藏  举报

导航