【0006】数据的压缩、解压缩——时间优先、空间优先
时间优先的方式实现数据的压缩、解压缩
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> // "aaaaabbbhaihualovefangfangooooooooo"; --> 5a3bhaihualovefangfang9o char * timefastzip(char *str) { int length = strlen(str); // 获取待压缩字符串的长度 char *newstr = (char *)calloc(length, sizeof(char)); // 给压缩的字符串开辟内存 char *pstr = str; char *pnewstr = newstr; // 保存分配内存的首地址 while (*pstr != '\0') { int charlength = 0; char * p = pstr; while (*p == *(p + 1)) { charlength++; // 统计重复字母次数 p++; } if (charlength == 0) *pnewstr++ = *pstr++; else { *pnewstr = charlength + 1 + '0'; // 重复字母个数转化为数值型字符 *(pnewstr + 1) = *pstr; pnewstr += 2; pstr += charlength + 1; } } _recalloc(newstr, strlen(newstr), sizeof(char)); // 释放压缩的空间 return newstr; } char * timefastunzip(char *str) { char *newstr = (char *)calloc(10000, sizeof(char)); char *pstr = str; char *pnewstr = newstr; while (*pstr != '\0') { char *p = pstr; if (*p >= '0'&&*p <= '9') { int length = *p - '0'; for (int i = 0; i < length; i++) { *pnewstr++ = *(p + 1); } pstr += 2; } else { *pnewstr++ = *pstr++; } } _recalloc(newstr, strlen(newstr), sizeof(char)); return newstr; } void main006() { char str[1024] = "aaaaabbbhaihualovefangfangooooooooo"; // 5a3bhaihualovefangfang9o printf("%s \n", str); printf("%s \n", timefastzip(str)); printf("%s \n", timefastunzip(str)); system("pause"); }
空间优先的方式实现数据的压缩、解压缩
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> // 双指针法操作字符串 // "aaaaabbbhaihualovefangfangooooooooo"; --> 5a3bhaihualovefangfang9o char * spacezipa(char *str) // 压缩字符串中的a { char *p1 = str; char *p2 = str; while (*p1 = *p2) { if (*p1 != 'a') { p1++; p2++; } else { p2++; } } return str; } char * spacezipX(char *str) // abhaihualovefangfango { char *p1 = str; char *p2 = str; while (*p1 = *p2) { int length = 1; while (*p1 == *p2) { p2++; } p1++; } return str; } char * spacezip(char *str) // 5a3bhaihualovefangfang9o { char *p1 = str; char *p2 = str; while (*p1 = *p2) { int length = 1; char *p3 = p2 + 1; while (*p1 == *p3) { p3++; length++; } if (length > 1) { *p1 = length + '0'; *(p1 + 1) = *(p3 - 1); p1 += 2; p2 += length; } else { p1++; p2++; } } return str; } char * spaceunzip(char *str) { char *p1 = str; char *p2 = str; while (*p1 = *p2) { int length = 0; if (*p1 >= '0'&&*p1 <= '9') { length = *p1 - '0'; } if (length == 0) { p1++; p2++; } else { char ch = *(p1 + 1); for (char *p = p1 + strlen(p1); p > p1 + 1; p--) // 5a 扣除两个字符 { *(p + length - 2) = *p; } for (int i = 0; i < length; i++) { *(p1 + i) = ch; } p1 += length; p2 = p1; } } return str; } void main007() { char str[1024] = "aaaaabbbhaihualovefangfangooooooooo"; // 5a3bhaihualovefangfang9o printf("%s \n", str); printf("%s \n", spacezip(str)); printf("%s \n", spaceunzip(str)); system("pause"); }