字符串压缩(华为2014,机试)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_RLEN 50

/* Returns the Run Length Encoded string for the
   source string src */
char *encode(char *src)
{
    int rLen;
    char count[MAX_RLEN];
    int len = strlen(src);

    /* If all characters in the source string are different,
      then size of destination string would be twice of input string.
      For example if the src is "abcd", then dest would be "a1b1c1d1"
      For other inputs, size would be less than twice.  */
    char *dest = (char *)malloc(sizeof(char)*(len*2 + 1));

    int i, j = 0, k;

    /* traverse the input string one by one */
    for(i = 0; i < len; i++)
    {

        /* Copy the first occurrence of the new character */
        dest[j++] = src[i];

        /* Count the number of occurrences of the new character */
        rLen = 1;
        while(i + 1 < len && src[i] == src[i+1])
        {
            rLen++;
            i++;
        }

        /* Store rLen in a character array count[] */
        sprintf(count, "%d", rLen);                 //防止数目过大

        /* Copy the count[] to destination */
        for(k = 0; *(count+k); k++, j++)
        {
            dest[j] = count[k];
        }
    }

    /*terminate the destination string */
    dest[j] = '\0';
    return dest;
}

/*driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    char *res = encode(str);
    printf("%s", res);
    getchar();
}
Time Complexity:O(n)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值