算法:华为面试代码题

题目:

找出字符串中的元音字符并按序构成字符串(小写字符和大写字符按序排列)。

1、元音字符:a,e,i,o,u, A,E,I,O,U

2、函数原型:void findObj(const char* s, char* out);

3、例: s = "xyzabc123BaUAUooe";  ==> out = "aaeooAUU";

有效代码如下:

#include<stdio.h>
#include<math.h>

typedef unsigned int u32;
typedef unsigned short int u16;
typedef unsigned char u8;
#define max 255
void findObj(const char* src,const char* obj,char* out)
{
char count[255]={0};
int i=0;//初始化很重要,要不然 i 的值无法确定
int j=0;
printf("%s\n", src);//
printf("%s\n", obj);
while(src[i])
{
printf("%d\n", src[i]);
count[src[i++]]++;

}
i=0;
while(obj[i])
{
for(j=0;j<count[obj[i]];j++)
{
*out++=obj[i];
}
i++;
}
*out=0;
}
int main()
{
u8 t;
printf("开始\n");
char tx[max];
for(t=0;t<max-1;t++)
{
tx[t]=0;
}
findObj("xyzabc123BaUAUooe","ae2AEIOU",tx);
printf("%s\n", tx);
return 0;
}

 

 

 依据ASSIC码表,创建一个数组,遍历查找的字符串,根据ASSIC表255个元素,count[src[i++]]++,有了对应的元素,则数组对应位置加1,比如a为120,字符串中有3个,则count[120]=3

 

 

 从printf("%d\n", obj[i]);处可知,根据输入参数const char* obj按序查找count数组中对应的值的数目,再依次 *out++=obj[i];赋值给结果字符串

从而实现时间复杂度O(n)  最坏情况循环次数为strlen(src) * 2

扩展性上,支持任意目标字符的自定义

 

posted @ 2020-10-28 13:01  txzing  阅读(501)  评论(0编辑  收藏  举报