字符串的解压缩

来源:互联网 发布:淘宝贷买家可以贷款吗 编辑:程序博客网 时间:2024/06/12 00:34

问题描述:对字符串进行解压缩

例如:5W1G2B ---> WWWWWGBB

解决方案:

1.将输入字符串分别为集合5W、1G、2B,每个集合由一个数字和一个字符构成

2.从尾到头读取字符串,当遇到一个字符的时候,保存下来;当遇到一个数字的时候,我们开始创建一个数,直到遇到下一个字符

3.当遇到下一个字符之前,我们应当扩展这个集合,例如(5W ---> WWWWW),并保存下来

4.因为遍历是从尾到头开始的,因此我们需要逆转这个输出结果。

#include <stdio.h>#include <string.h>#include <math.h>#include <ctype.h>#include <malloc.h>/* Reversal of a string */void strreverse(char* str){      int i;      char cpstr[strlen(str)+1];      for(i=0; i < strlen(str); i++)      {        cpstr[i] = str[strlen(str)-i-1];      }      cpstr[strlen(str)] = '\0';      strcpy(str, cpstr);}/* Expand a set (5W ---> wwwww). here num = 5; byte = W; str is where the expansion is stored */void putStringRep(int num,char byte,char* str){   int i;   for(i=0;i<num;i++)   {      str[i] = byte;   }   str[num] = '\0';}int main(){int i;intplace = 0;int number = 0; char byte;char *temp;char input[] = "12W5B1G6W";//this is just for sake of the example. In reality size cannot be fixed herechar output[100];for(i = strlen(input)-1; i>=-1; i--){//current byte is a letter. reason for i < 0 is because otherwise//the processing will get skipped for the first set if(isalpha(input[i]) || i < 0) {//a number was previously stored, that means 'byte' and 'number' together form a setif(number != 0) {//process this set//create a temp string as long as the num (+1 for )temp = (char*)malloc(sizeof(char)*(number+1));//expand the set and store the expansion in tempputStringRep(number,byte,temp);strcat(output,temp);//add the set to the output stringfree(temp);//释放temp指针 } byte = input[i]; //now proceed to capture the currently marked byte//nullify these values in order to grab the next set's number number = 0;  place = 0;}else if(isdigit(input[i])) //当前字符是数字 { //store the digit. for a sequence of digits, the place will determine//whether the digit goes into unit's place, ten's place, hundred's place etc.number += (int)pow(10,place) * ((int)(input[i]) - (int)('0'));place++;}}strreverse(output);//逆转输出     printf("input:%s\n",input);printf("output:%s\n",output);return 0;}

原创粉丝点击