zoukankan      html  css  js  c++  java
  • 算法:华为面试代码题

    题目:

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

    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 ", src);//
    printf("%s ", obj);
    while(src[i])
    {
    printf("%d ", 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("开始 ");
    char tx[max];
    for(t=0;t<max-1;t++)
    {
    tx[t]=0;
    }
    findObj("xyzabc123BaUAUooe","ae2AEIOU",tx);
    printf("%s ", tx);
    return 0;
    }

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

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

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

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

  • 相关阅读:
    SQL JOB
    Log4net配置
    教你怎么使用Windows7系统自带的备份与还原的方法
    在LINQ TO SQL 中使用MVC3中的DataAnnotations 【MetadataType】
    图片下载
    DOS的一些常用命令
    自动合并多个文件如js css等 可以增加效率
    利用$.getJSON() 跨域请求操作
    在razor中使用递归,巧用递归
    Use ASP.NET and DotNetZip to Create and Extract ZIP Files
  • 原文地址:https://www.cnblogs.com/txzing/p/13890434.html
Copyright © 2011-2022 走看看