9月5日 华为2014校园招聘的机试题目_C语言版答案

手有些生了。算法

题目:函数

经过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重复字母进行压缩,并输出压缩后的字符串。
压缩规则:
一、仅压缩连续重复出现的字符。好比字符串”abcbc”因为无连续重复字符,压缩后的字符串仍是”abcbc”。
二、压缩字段的格式为”字符重复的次数+字符”。例如:字符串”xxxyyyyyyz”压缩后就成为”3x6yz”。
要求实现函数:
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);
输入pInputStr: 输入字符串lInputLen: 输入字符串长度
输出 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;
注意:只须要完成该函数功能算法,中间不须要有任何IO的输入输出
示例
输入:“cccddecc” 输出:“3c2de2c”
输入:“adef” 输出:“adef”
输入:“pppppppp” 输出:“8p”spa

 1 /*
 2  * by feifei435
 3  */
 4 #include <stdio.h>
 5 #include <stdlib.h>
 6 #include <string.h>
 7  
 8 void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr)
 9 {
10     int i = 0;
11     int same_begin = 0;
12     int same_end = 0;
13     char last_char = 0;
14     while (i <= (lInputLen - 1))
15     {
16         last_char = pInputStr[i];
17         if (pInputStr[i+1] == last_char)
18         {
19             if(same_end == 0)
20             {
21                 same_begin =i;
22                 same_end = i+1;
23             }
24             else
25             {
26                 same_end++;
27             }
28         }
29         else 
30         {
31             if(same_end != 0)//结束连续
32             {
33                 pOutputStr[strlen(pOutputStr)] = pInputStr[same_begin];
34                 itoa((same_end - same_begin + 1), &pOutputStr[strlen(pOutputStr)], 10);
35                 same_begin = 0;
36                 same_end = 0;
37             }
38             else
39             {
40                 pOutputStr[strlen(pOutputStr)] = pInputStr[i];
41             }
42         }
43         i++;
44     }
45 }
46  
47 int main()
48 {
49     char str [80] = {0};
50     char strZip[80] = {0};
51     printf("Input the str to be compressed:\n");
52     scanf("%s",str);
53     stringZip(str, strlen(str), strZip);
54     printf("%s\n",strZip);
55  
56     return 0;
57 }
相关文章
相关标签/搜索