现在的位置: 首页 > 综合 > 正文

第十六题 2014华为机试题 字符串压缩程序

2017年12月25日 ⁄ 综合 ⁄ 共 771字 ⁄ 字号 评论关闭

通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
压缩规则:
    1、仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc"。

    2、压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"。

//华为机试题
#include <iostream>
using namespace std;
void compressStrings(char *str)
{
	if (str==nullptr)
	{
		return;
	}
	int tempLen = 0;
	char *tempstr=str;
    
	while (*tempstr)
	{
		char begstr=*tempstr;
		int strcount=0;
		while (*tempstr==begstr)
		{
			tempstr++;
			strcount++;
		}
		char nextstr=*tempstr;
		if (strcount>1)
		{
			//sprintf(str+tempLen,"%d%c",strcount,begstr);
			sprintf_s(str,strlen(str),"%d%c",strcount,begstr);
		}
		else
		{
			//sprintf(str+tempLen,"%c",begstr);
			sprintf_s(str,strlen(str),"%c",begstr);
		}
		tempLen=strlen(str);
		*(str+tempLen)=nextstr;
	}
	*(str+tempLen)='\0';
	cout<<str<<endl;
	
}
int main()
{
    char str[] = "aaaaaaabcdddedf";
    compressStrings(str);
    return 0;
}

抱歉!评论已关闭.