- 难得有空,玩玩今年的面试题:<p> </p><p>9月5日,华为2014校园招聘的机试题目
- 通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
- 压缩规则:
- 1、仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc"。
- 2、压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"。
- 要求实现函数:
- void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);
- <span style="font-family:Microsoft YaHei;"> 输入pInputStr</span>: 输入字符串lInputLen: 输入字符串长度
- <span style="font-family:Microsoft YaHei;"> 输出 pOutputStr</span>: 输出字符串,空间已经开辟好,与输入字符串等长;
- <span style="font-family:Microsoft YaHei;">注意:</span>只需要完成该函数功能算法,中间不需要有任何IO的输入输出
- 示例
- 输入:“cccddecc” 输出:“3c2de2c”
- 输入:“adef” 输出:“adef”
- 输入:“pppppppp” 输出:“8p”
- </p>
- /*----------------------------------------------*\
- 玩玩2014年华为的机试题
- mengyafei43@gmail.com
- \*----------------------------------------------*/
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- #define MAX_LENGHT (1024)
- void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);
- int main(int argc, char* argv[])
- {
- char src[MAX_LENGHT] = {0};//输入字符串
- char dst[MAX_LENGHT] = {0};//输出字符串
- cin>>src;
- int i=0;
- while(src[i++]){};//求字符串长度
- stringZip(src,i-1,dst);
- cout<<"Input String is:"<<src<<endl;
- cout<<"Zip String is:"<<dst<<endl;
- return 0;
- }
- void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr)
- {
- int i=0;
- int j=0;
- char list_c[MAX_LENGHT];//list char
- int list_n[MAX_LENGHT]; //list num
- int list_idx = 0;
- for(i=0;i<lInputLen;i++)
- {
- char cTemp = pInputStr[i];
- if(list_idx <=0)
- {
- list_c[list_idx] = cTemp;
- list_n[list_idx] = 1;
- list_idx = 1;
- }
- else
- {
- if(list_c[list_idx-1] != cTemp)
- {
- list_c[list_idx] = cTemp;
- list_n[list_idx] = 1;
- list_idx++;
- }
- else
- {
- list_n[list_idx-1] += 1;
- }
- }
- }
- for(i=0;i<list_idx;i++)
- {
- sprintf(&pOutputStr[j],"%d%c",list_n[i],list_c[i]);
- j+=2;
- }
- }