0443.cpp (670B)
1 class Solution { 2 public: 3 int compress(vector<char> &chars) { 4 char prev = chars[0]; 5 int count = 1, crnt = 0; 6 for (int i = 1; i < chars.size(); i++) { 7 if (chars[i] == prev) 8 count++; 9 else { 10 chars[crnt++] = prev; 11 if (count != 1) 12 for (char c : to_string(count)) 13 chars[crnt++] = c; 14 count = 1; 15 prev = chars[i]; 16 } 17 } 18 chars[crnt++] = prev; 19 if (count != 1) 20 for (char c : to_string(count)) 21 chars[crnt++] = c; 22 23 return crnt; 24 } 25 };