題目描述:
通過鍵盤輸入一串小寫字母(a~z)組成的字符串。請編寫一個字符串壓縮程序,將字符串中連續出席的重複字母進行壓縮,並輸出壓縮後的字符串。
壓縮規則:
1. 僅壓縮連續重複出現的字符。比如字符串"abcbc"由於無連續重複字符,壓縮後的字符串還是"abcbc".
2. 壓縮字段的格式爲"字符重複的次數+字符"。例如:字符串"xxxyyyyyyz"壓縮後就成爲"3x6yz"
要求實現函數:
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);
【輸入】 pInputStr: 輸入字符串
lInputLen: 輸入字符串長度
【輸出】 pOutputStr: 輸出字符串,空間已經開闢好,與輸入字符串等長;
【注意】只需要完成該函數功能算法,中間不需要有任何IO的輸入輸出
示例
輸入:“cccddecc” 輸出:“3c2de2c”
輸入:“adef” 輸出:“adef”
輸入:“pppppppp” 輸出:“8p”
用C語言實現的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void stringZip(const char *pInputStr, long lInputLen,char *pOutputStr)
{
int i=0,j=0;
int repeat=1;
pOutputStr = (char *)malloc(lInputLen+1);
assert(pInputStr!=NULL);
assert(pOutputStr!=NULL);
while((i+1)<=lInputLen)
{
while(*(pInputStr+i)==*(pInputStr+i+1))
{
repeat++;
i++;
}
if(repeat==1)
{
*(pOutputStr+j)=*(pInputStr+i);
i++;
j++;
}
else
{
*(pOutputStr+j) = repeat+'0'; //把數字轉換成字符串
repeat = 1;
j++;
}
}
if(*(pInputStr+lInputLen-1)!=*(pInputStr+lInputLen))
*(pOutputStr+j)=*(pInputStr+lInputLen);
printf("pOutputStr:");
i=0;
while(i<j)
{
printf("%c",*(pOutputStr+i));
i++;
}
printf("\n");
}
void main()
{
long lInputLen = 0;
char c;
char *pOutputStr = NULL;
char *pInputStr = (char *)malloc(100);
printf("pInputStr:");
*(pInputStr+lInputLen)=getchar();
while((*(pInputStr+lInputLen))>='a'&&(*(pInputStr+lInputLen))<='z')
{
lInputLen++;
*(pInputStr+lInputLen)=getchar();
}
printf("lInputLen: %d\n",lInputLen);
stringZip(pInputStr,lInputLen,pOutputStr);
}