时间优先字符串压缩与解压缩
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include<string.h>
4 #include<malloc.h>
5 #include <memory.h>
6
7 // 时间优先
8 char * timefastzip(char *str)
9 {
10 int length = strlen(str);//获取长度
11 char *newstr = calloc(length + 1, 1);//分配内存
12
13 char *p = str;
14 char *newp = newstr;//备份
15 while (*p != '\0')
16 {
17 char *pis = p;//标识当前指针
18 char ch = *pis;//当前字符
19 int strlength = 0;
20
21 while ((*pis) == (*(pis + 1)))//如果相等
22 {
23 pis++;//指针移动
24 strlength++;//计数
25 }
26
27 if (strlength == 0)
28 {
29 /*
30 *newp = *p;
31 newp++;
32 p++;
33 */
34 *newp++ = *p++;
35
36 }
37 else
38 {
39 *newp = strlength + 1 + '0';//转化为字符
40 *(newp + 1) = *p;//保存字符
41 newp += 2;
42 p += strlength + 1;//指针往前移动
43 }
44 }
45
46 length = strlen(newstr);//新的长度
47
48 newstr = _recalloc(newstr, length + 1, 1);//压缩内存
49
50 return newstr;
51 }
52
53 char * timefastunzip(char *str)
54 {
55 char *newstr = calloc(10000, 1);//分配缓冲区
56 char *p = str;
57 char *newp = newstr;//备份
58 while (*p != '\0')
59 {
60 char *pis = p;
61 if (*pis >= '0' && *pis <= '9')
62 {
63 int length = *pis - '0';//长度
64 for (int i = 0; i < length; i++)//拷贝字符
65 {
66 *newp++ = *(pis + 1);
67 }
68 p += 2;//指针下移动
69 }
70 else
71 {
72 *newp++ = *p++;//常规,直接拷贝
73 }
74 }
75
76 int length = strlen(newstr);//新的长度
77
78 newstr = _recalloc(newstr, length + 1, 1);//压缩内存
79
80 return newstr;
81
82 }
83 void main()
84 {
85 char str[1024] = "aaaaabbhelloworldccccccccc";
86
87 printf("压缩之前:%s\n", str);
88
89 printf("压缩之后:%s\n", timefastzip(str));
90
91 printf("解压缩之后:%s\n", timefastunzip(timefastzip(str)));
92
93 system("pause");
94 }
长风破浪会有时,直挂云帆济沧海
posted on 2015-05-16 21:53 Dragon-wuxl 阅读(124) 评论(0) 收藏 举报
浙公网安备 33010602011771号