Leetcode 443. String Compression

443. String Compression
(如果没有把大的逻辑先定下来,写这种题就是找死啊)
Easy
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?
class Solution {
public:
    int compress(vector<char>& chars) {
        int i = 0;
        const int size = chars.size();
        if(size < 2){
            return size;
        }
        int cnt = 1;
        for(int j = 1; j < size; j++){
            if(chars[j] == chars[j - 1]){
                cnt++;
            }
            else{
                if(cnt >= 2){
                    chars[i++] = chars[j - 1];
                   
                    for(auto k : to_string(cnt)){
                       chars[i++] = k;
                    }
           
                    cnt = 1;
                }
                else{
                    chars[i++] = chars[j - 1];
                }
            }
        }
        if(cnt >= 2){
            chars[i++] = chars[size - 1];
            for(auto k : to_string(cnt)){
                       chars[i++] = k;
            }
           
        }
        else{
            chars[i++] = chars[size - 1];
        }
        return i;
    }
};

Comments

Popular posts from this blog

1427. Split Array into Fibonacci Sequence

Amazon OA 763. Partition Labels

05/25 周一