通過鍵盤輸入一串小寫字母(a~z)組成的字元串。請編寫一個字元串壓縮程式,将字元串中連續出席的重複字母進行壓縮,并輸出壓縮後的字元串。
壓縮規則:
1. 僅壓縮連續重複出現的字元。比如字元串"abcbc"由于無連續重複字元,壓縮後的字元串還是"abcbc".
2. 壓縮字段的格式為"字元重複的次數+字元"。例如:字元串"xxxyyyyyyz"壓縮後就成為"3x6yz"
要求實作函數:
void stringZip(const char*pInputStr, long lInputLen, char *pOutputStr);
【輸入】 pInputStr: 輸入字元串
lInputLen: 輸入字元串長度
【輸出】 pOutputStr: 輸出字元串,空間已經開辟好,與輸入字元串等長;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void stringZip(const char* pInputStr,long lInputLen,char* pOutputStr)
{
if(pInputStr==NULL||lInputLen<=0)
return;
int k=0;
int count=1;
char tmp=pInputStr[0];
for(int i=1;i<lInputLen;i++){
while(pInputStr[i]==tmp){
++count;
++i;
}
if(count==1)
pOutputStr[k++]=tmp;
else{
if(count>=10){
int numBit[10];
int t=0;
do{
numBit[t++]=count%10;
}while(count/=10);
for(int j=t-1;j>=0;j--){
pOutputStr[k++]=numBit[j]+'0';
}
}
else
pOutputStr[k++]=count+'0';
pOutputStr[k++]=tmp;
count=1;
}
tmp=pInputStr[i];
}
pOutputStr[k]='\0';
printf("%s",pOutputStr);
}
int main()
{
char* Instr="xxxxxxxxxxxxxyyyaaas";
long len=strlen(Instr);
char* Outstr=(char *)malloc(len+1);
stringZip(Instr,len,Outstr);
free(Outstr);
return 0;
}