【剑指】面试题50 字符串中第一个只出现一次的字符

来源:互联网 发布:网络用语马克啥意思 编辑:程序博客网 时间:2024/06/05 06:28

算法思想
       我们可以考虑实现一个简单的哈希表,字符是一个长度为8的数据类型,因此共有256中可能。于是我们创建一个长度为256的数组,每个字母根据其ASCII吗值作为数组的下标对应数组的一个数字,而数组中存储的每个字符出现的次数,这样我们创建了一个大小为256、以字符ASCII码值为键值的哈希表
      

char FirstNotRepeatingChar(string str) {    if (str.c_str() == NULL)        return '\0';    const int tablesize = 256;    unsigned int hashTable[tablesize] = { 0 };    const char* key = str.c_str();    while (*key != '\0'){        hashTable[*key]++;        key++;    }    key = str.c_str();    while (*key != '\0'){        if (hashTable[*key] == 1)            return *key;        key++;    }    return '\0';}
阅读全文
0 0
原创粉丝点击