```
class Solution {
public:
int compress(vector<char>& chars) {
int rep = 0;
int j = 0;
for (int i = 0; i < chars.size(); i++) {
rep++;
if (i == chars.size() - 1 || chars[i + 1] != chars[i]) {
chars[j++] = chars[i];
if (rep == 2) {
chars[j++] = '2';
}
else if (rep > 2) {
int j0 = j;
while (rep) {
chars[j++] = '0' + rep % 10;
rep /= 10;
}
reverse(chars.begin() + j0, chars.begin() + j);
}
rep = 0;
}
}
return j;
}
};
```