字符串壓縮程序

//	通過鍵盤輸入一串小寫字母(a~z)組成的字符串。請編寫一個字符串壓縮程序,將字符串中連續出席的重複字母進行壓縮,並輸出壓縮後的字符串。
//	壓縮規則:
//	1、僅壓縮連續重複出現的字符。比如字符串"abcbc"由於無連續重複字符,壓縮後的字符串還是"abcbc"。
//	2、壓縮字段的格式爲"字符重複的次數+字符"。例如:字符串"xxxyyyyyyz"壓縮後就成爲"3x6yz"。
//

#include <iostream>
#include <cassert>

using namespace  std;

void stringZip(const char *pInputStr, long InputLen, char *pOutputStr)
{
	assert(pInputStr != NULL);
	const char *p = pInputStr ;
	int *q = new int[InputLen +1] ;
	 int i = 0;
	 int count = 1;

	 pOutputStr[i++] = *p ;
	 p++ ;
	 while (*p != '\0')
	 {
		 if ( *p == pOutputStr[i-1] )
		 {
			 count++;
			 p++;
		 }
		 else
		 {
			 pOutputStr[i++] = '0' + count%10;
			 pOutputStr[i++] = *p ;
			  count = 1;
			 p++;
		 }
	 }
	 pOutputStr[i++] =  '0' + count%10;
	 pOutputStr[i] = '\0';
}

int main( )
{
	char input[] = "cdeca" ;
	char *output = new char[strlen(input)+1] ;
	stringZip(input, strlen(input), output );
	cout << output <<endl;
	//delete output ;
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章