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 }
相關文章
相關標籤/搜索