# LeetCode: 443. 压缩字符串¶

## 1、题目描述¶

输入：
["a","a","b","b","c","c","c"]

"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。


输入：
["a"]



输入：
["a","b","b","b","b","b","b","b","b","b","b","b","b"]



1. 所有字符都有一个ASCII值在[35, 126]区间内。
2. 1 <= len(chars) <= 1000

## 2、解题思路¶

char *numToString(int num) {
int digits = 1;

int temp = num;
while (temp / 10) {
digits++;
temp /= 10;
}

char *result = (char *) calloc(digits + 1, sizeof(char));

sprintf(result, "%d", num);

return result;

}

int compress(char *chars, int charsSize) {

int pos = 0;
char cur_ch = chars[0];

int ch_count = 1;
char *count;

for (int i = 1; i < charsSize; i++) {
if (chars[i] == cur_ch) {
ch_count++;

} else {
chars[pos++] = cur_ch;
cur_ch = chars[i];
if (ch_count >= 2) {
count = numToString(ch_count);
for (int j = 0; j < strlen(count); j++) {
chars[pos++] = count[j];
}
}
ch_count = 1;
}

}

chars[pos++] = cur_ch;

if (ch_count >= 2) {
count = numToString(ch_count);
for (int j = 0; j < strlen(count); j++) {
chars[pos++] = count[j];
}
}

return pos;

}