首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

华为2014校园招聘的机考题目解答——字符串压缩

2013-10-01 
华为2014校园招聘的机试题目解答——字符串压缩题目来源:JULY博客 http://blog.csdn.net/v_july_v/article/d

华为2014校园招聘的机试题目解答——字符串压缩

题目来源:JULY博客 http://blog.csdn.net/v_july_v/article/details/11921021

通过键盘输入一串小写字母(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>void stringZip(const char *pInputStr, long iInputLen, char *pOutputStr){const char *tempInput;char *tempOutput;char *temp = (char*)malloc(sizeof(char));long count=0;tempInput = pInputStr;tempOutput = pOutputStr;*temp = *tempInput;tempInput++;count = 1;while(iInputLen){iInputLen--;if (*temp != *tempInput){if (count > 1){char *str = (char*)malloc(sizeof(char));sprintf(str,"%d",count);//将long型计数变量转换为字符串while(*str) //解决long型变量转换为字符串后可能有多位的现象{*(tempOutput) = *str;tempOutput++;str++;}*(tempOutput) = *temp;tempOutput++;}else{*(tempOutput) = *temp;tempOutput++;}*temp = *tempInput;tempInput++;count = 1;}else{count++;tempInput++;}}*tempOutput = '\0';}void main(){char *str = "pxxxxxxxxxxxx";char *output = (char*)malloc(sizeof(str));stringZip(str, 13, output);printf(output);system("PAUSE");}

热点排行