cracking the coding interview No1.5

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);
	}
}


你可能感兴趣的:(cracking the coding interview No1.5)