leetcode字符串压缩,三指针实现。
int compress(char* chars, int charsSize){
if (chars == NULL || charsSize <0)
return -1;
if (charsSize <= 1)
return charsSize;
char * start = chars;
char * end = chars;
char * pos_w = chars;
char tmp[5];
int count = 0;
int i;
while (*start != '\0')
{
while (*end == *start && *end != '\0')
{
count++;
end++;
}
if (count == 1 && start > pos_w)
{
*pos_w = *start;
pos_w++;
}
else if (count == 1 && start == pos_w)
{
pos_w++;
}
else
{
*pos_w = *start;
pos_w++;
if (count > 10)
{
i = 0;
memset(tmp,0,sizeof(tmp));
while(count != 0)
{
tmp[i++] = count%10 + '0';
count = count/10;
}
i--;
while(i >= 0)
{
*pos_w = tmp[i--];
pos_w++;
}
}
else
{
*pos_w = '0' + count;
pos_w++;
}
}
start = end;
count = 0;
}
*pos_w = '\0';
return strlen(chars);
}