压缩字符串

来源:互联网 发布:淘宝直播微淘粉丝要求 编辑:程序博客网 时间:2024/06/08 02:39
问题:将"abbbbcccdddff"压缩为a4b3c3d2f

      

思路:首先计算出有几个不同的字符,再将每个字符的个数存在一个数组, 最后使用循环压缩,定义i和j,一个指向放的位置,一个指向放的内容;

#include <stdio.h>#include <stdlib.h>#include <string.h>void compress(char *p){char *cur = p;char *duff = p;int count = 0;int i = 0;int j = 0;int k = 0;int len = strlen(p);while (*duff++){                           //计算有几个不同的字符while (*(duff) == *(duff + 1)){duff++;}count++;}int *ptr = (int *)malloc(count*sizeof(int));  // 动态开辟存放每个元素个数的数组if (ptr == NULL){perror("use malloc");exit(EXIT_FAILURE);}memset(ptr, 0, count*sizeof(int));for (i = 0; i < count; i++){               // 计算数组的每个元素 (从0开始的)while (*(cur) == *(cur + 1)){ptr[i]++;cur++;}cur++;}printf("%s\n", p);for (k = 0; k < count; k++)             //压缩字符串{if (ptr[k] != 0){                   //一个字符不用压缩for (i = 0, j = 0; j < len + 1; i++, j++){  //len+1 将'\0'赋值过去if (p[j] == p[j + 1]){p[i] = ptr[k] + '0' + 1;   //将整形数字转化为字符型数字   加1因为数组从0开始 j += ptr[k];i++;k++;}p[i] = p[j];}}}printf("%s\n",p);free(ptr);ptr = NULL;}int main(){char str[] = "abbbbcccdddff";// a4b3c3d2fcompress(str);system("pause");return 0;}