華為的最新的兩道算法設計題


要求均用C語言實現

1.找出最大長度子字符串(只包含字母),打印並且返回長度。 例如 str = "abc123abcd234abcdefgha324adsdawqdasdaseqqwe345abchded",最大子字符串是

“adsdawqdasdaseqqwe”

 1 int findMaxSubstring(char* str)
 2 {
 3     int maxLength = 0;
 4     int maxStartIndex = 0;
 5     int curLength = 0;
 6     int curStartIndex = 0;
 7     bool isFind = 0;
 8     for(unsigned int i = 0;i<strlen(str);i++)
 9     {
10         if(str[i] >= 'a' && str[i] <= 'z')
11         {
12             if(isFind == 0)
13             {
14                 isFind = 1;
15                 curLength = 1;
16                 curStartIndex = i;
17             }
18             else
19             {
20                 curLength++;
21             }
22         }
23         else if (str[i] < 'a' || str[i] > 'z')
24         {
25            isFind = 0;
26            if(curLength > maxLength)
27            {
28               maxLength = curLength;
29               maxStartIndex = curStartIndex;
30               curLength = 0;
31            }
32         }
33     }
34     char *p = NULL;
35     p = &str[maxStartIndex];
36     while(*p >= 'a' && *p <= 'z')
37     {
38         putchar(*p);
39         p++;
40     }
41     return maxLength;
42 }

 

2. 一個四位數,如1024,1004,打印出他們的中文形式,如果一千零二十四,一千零四

 這題因為限定了4位數,所以只考慮了4位數的情況,吃點分享一個大小寫轉換的源碼,里面有不限位數的情況,當時調試的很痛苦,思想差不多。

void iConvert(int digit)
{
    char a[5][10] = {"","","","",""};
    char b[11][10] = {"","","","","","","","","","",""};
    char result[50] = {'\0'};
    int A[4] = {};
    for(int i=3;i>=0;i--)
    {
        A[i] = digit % 10;
        digit = int(digit/10);
    }
    printf("%d,%d,%d,%d\n",A[0],A[1],A[2],A[3]);
    int foundZero = 0;
    for(int i = 0 ;i<4;i++)
    {
        if(A[i]>0)
        {
            strcat(result,b[A[i]]);
            strcat(result,a[i]);
        }
        if(A[i]==0 && foundZero == 0)
        {
           if(i!=3)//如果不是最后一位,則不追加零
           {
             strcat(result,a[4]);
             foundZero = 1;
           }
        }    
    }
    puts(result);
}

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM