C++ O(n) time O(1) space


  • 0
    class Solution {
    public:
        int compress(vector<char>& chars) {
            int n = chars.size();
            int cnt = 1, idx = 1;
            for (int i = 1; i <= n; ++i) {
                if (i < n && chars[i] == chars[i-1]) {
                    ++cnt;
                    continue;
                } else if (cnt > 1) {
                    string s = to_string(cnt);
                    for (char c: s) chars[idx++] = c;
                } 
                if (i < n) {
                    chars[idx++] = chars[i];
                    cnt = 1;
                }
            }
            return idx;
        }
    };
    

Log in to reply
 

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