C++ solution O(N)


  • 0
    G
    class Solution {
    public:
        int compress(vector<char>& v) {
            
            int w = 0;
            for(int r = 1,count = 1; r <= v.size(); ++r){
                if(r!= v.size() && v[r] == v[r - 1]){
                    count++;
                }
                else{
                    v[w++] = v[r - 1];
                    
                    if(count != 1){
                        ostringstream ss;
                        ss << count;
                        for(auto &c : ss.str()){
                            v[w++] = c;
                        }
                    }
                    
                    count = 1;
                }
            }
            
            return w;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.