您的位置:首页 > 其它

cracking the coding interview No1.5

2014-10-19 16:21 399 查看
1.5 Implement a method to perform basic string compression using the counts of repeated characters.For example.

For example,the string aabcccccaaa would become a2b1c5a3.If the “compressed”string would not become smaller

than the original string,your method should return the original string.

void change(char *str)
{
	if (str == NULL)
		return;
	int count = 0,length = strlen(str);
	int k = 0;
	char c = str[0];
	char *laststring = new char[length+1];
	
	for (int i = 0;i < length;i++)
	{
		if (c == str[i])
		{
			count++;
		}
		else
		{
			laststring[k++] = c;
			laststring[k++] = count+'0';
			c = str[i];
			count = 0;
		}	

	}
	laststring[k] = '\0';
	if (k > length)
	{
		printf("%s\n",str);
	}
	else
	{
		printf("%s\n",laststring);
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: