Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5644078
  • 博文数量: 291
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 7924
  • 用 户 组: 普通用户
  • 注册时间: 2016-07-06 14:28
个人简介

阿里巴巴是个快乐的青年

文章分类

全部博文(291)

文章存档

2018年(21)

2017年(4)

2016年(5)

2015年(17)

2014年(68)

2013年(174)

2012年(2)

分类: 架构设计与优化

2013-05-14 15:03:53

一、原理
        在网络传输中或者语音视频通信中,为了减少传输带宽,数据压缩应运而生,字符串压缩尤为常见,比如:abbbcdddd,压缩后为a1b3c1d4。
        设置计数器count,遍历一遍字符串,每次指针移动一个字符,判断当前字符是否与前一字符相等,如果相等,则计数器count加1,指针继续下移,否则,对已经遍历的字符串进行处理,然后重新初始化计数器count,如此这般直到字符串遍历结束。

二、实现
        #include    

        char* compress(char *i_szArray, char *o_szArray)
        {
            if ((NULL == i_szArray) || (NULL == o_szArray))
            {
                return NULL;
            }

            int count = 1;
            int index = 0;
            int i = 0;
            char *temp = i_szArray;
            for (i=1; *temp++!='\0'; i++)
            {
                if (i_szArray[i] == i_szArray[i-1])
                {
                    ++count;
                }
                else
                {
                    o_szArray[index] = i_szArray[i-1];
                    ++index;
                    sprintf(o_szArray+index, "%d", count);
                    count = 1;
                    ++index;
                }
            }

            return o_szArray;
        }

        int main()
        {
            char i_szArray[] = "abbbcdddd";
            char o_szArray[10] = {0};
            printf("src=%s-->dest=%s\n", i_szArray, o_szArray);
            printf("src=%s-->dest=%s\n", i_szArray, compress(i_szArray, o_szArray));

            return 0;
        }






阅读(2498) | 评论(4) | 转发(1) |
1

上一篇:字符串之回文

下一篇:字符串之包含

给主人留下些什么吧!~~

yuccn2013-12-10 11:00:04

“淘宝高级开发工程师” 2010年的号了,还写出这种算法,汗~~~

yuccn2013-12-10 10:58:02

留言居然被折断了?
else 分支有个明显的错误,
ddddddddddddddddddaab这种字符串,只要某一个字母连续出现超过9 那么你的算法就出错下,好好测试下吧,

yuccn2013-12-10 10:52:20

else
                {
                    o_szArray[index] = i_szArray[i-1];
                    ++index;
                    sprintf(o_szArray+index, "%d", count);

scq2099yt2013-05-14 15:04:08

文明上网,理性发言...