我做了两个假设并编写了这段代码,
我们的空间是我们正在编码的字符串大小的两倍。即,假设我们正在编码“ab”,那么分配的空间空间应该至少为 4 个字节。
字母的连续条纹最多可以是 999。如果有可能在相邻位置有 1000 个相同的字符,那么我们必须相应地增加“count_str”字符数组的大小。
#include <stdio.h>
#include <string.h>
char *compress(char *input) {
int i = 0;
int count = 1;
int k = 0;
int j = 0;
int len = 0;
int digits_in_count = 0;
char count_str[3];
int m = 0;
for(i = 0; i < strlen(input); i++) {
j = i+1;
m = 0;
count = 1;
len = strlen(input);
printf("\niteration: %d, string = %s",i, input);
while((input[j] != '\0') && (input[j] == input[i])) {
count++;
j++;
}
sprintf(count_str, "%d", count);
digits_in_count = strlen(count_str);
//this means we have reaced last alphabet in the string
if(input[j] == '\0' && count == 1) {
k = k+1;
goto count_append;
}
input[k++] = input[i];
// we are assuming that we have enough space in the end, to move string.
// we are memmove for remaining portion of the string.
// if the string is "aaab", then we have to move 'b' one step ahead
// and it will look like "aab", later in the end we are adding count,
// and making it as "a3b".
// if the string is "ab", then we have to move 'b' one step away,
// to make space for adding 'count'.
// and the new string after memmove will looklike "abb",
// in the end we are adding count and making it as "a1b"
// memmove will not hit for last character in the string, because there
// is already enough space for appending 'count'.
memmove((input+i+digits_in_count+1) , input+j, len-j+1);
i = i+digits_in_count;
count_append:
{
while(digits_in_count) {
input[k++] = *(count_str+m);
m = m+1;
digits_in_count--;
}
}
}
return input;
}
void main()
{
char arr[50] = "aaab";
printf("\n%s\n", compress(arr));
}