2016奇虎360研发工程师内推笔试编程题第一题

来源:互联网 发布:gotv源码资源吧 编辑:程序博客网 时间:2024/05/01 00:40

寻找字符串中第一个只出现一次的字符

正在挑战一个CrackMe的你,把需要填写的前面几位密码都正确猜出了,可是这最后一位密码,好像藏得有点深。CrackMe的作者还挑衅般的在里面藏了个.tar.gz文件,解压缩出来,里面写道
你要的最后一个字符就在下面这个字符串里,这个字符是下面整个字符串中第一个只出现一次的字符。(比如,串是abaccdeff,那么正确字符就是b了) 然而下面给出来的字符串好像太长太长了,单靠人力完全无法找出来。
于是,你需要写一个程序代劳了。

输入

2
sesadfd
dddasdxx

输出

e
a

实现思路

该题需要统计每个字符的数量,如果使用其他支持关联数组的语言,使用关联数组是最简单的,而在 C 语言中,可以使用哈希表来代替,但是自己实现哈希表又太麻烦,这题正好 hash(char) -> int,并且完全没有“哈希冲突”,因此可以使用数组来代替哈希表。

每个字符串只要进行三个循环就可以得到答案了,时间复杂度为 T(N)。

代码

#include <stdio.h>#include <string.h>#include <stdlib.h>#defince MAX 1000000char getChar(char *str);int main() {    int T, i, j;    char str[MAX+5], res;    scanf("%d", &T);    while(T--) {        scanf("%s", str);        res = getChar(str);        printf("%c\n", res);    }    return 0;}/* * 时间复杂度为 T(N) */ char getChar(char *str) {    int i = 0, hash[127];  //  可打印的字符(0x21, 0x7F)转成整型时,最大为 127    char a = 'a', chr, res = 'a';    //  遍历字符串,初始化数组 ,数组空间利用率为 30/127     for (;;) {        chr = str[i++];        if (chr == '\0') {            break;        }        hash[int(chr)] = 0;     }    i = 0;    //  遍历字符串,将出现过的 key 的 value++     for (;;) {        chr = str[i++];        if (chr == '\0') {            break;        }        hash[int(chr)]++;     }    i = 0;    //  遍历字符串,将 value 为 1 的 key 找出来    for (;;) {        chr = str[i++];        if (chr == '\0') {            break;        }        if (hash[int(chr)] == 1) {            res = chr;            break;        }    }    return res;}
1 0