华为的最新的两道算法设计题

要求均用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] = {''};
    int A[4] = {};
    for(int i=3;i>=0;i--)
    {
        A[i] = digit % 10;
        digit = int(digit/10);
    }
    printf("%d,%d,%d,%d
",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);
}

运行结果:
原文地址:https://www.cnblogs.com/amsun/p/3454802.html