字符串的解压缩

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

例如: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;
	int	place = 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 here
	char 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 set
			if(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 temp
				putStringRep(number,byte,temp);

				strcat(output,temp);	//add the set to the output string

				free(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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值