《剑指offer》第五十题I:字符串中第一个只出现一次的字符

// 面试题50(一):字符串中第一个只出现一次的字符
// 题目:在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输出
// 'b'。

#include <cstdio>
#include <string>

char FirstNotRepeatingChar(const char* pString)
{
    if (pString == nullptr)
        return '';

    const int tableSize = 256;  //char为8位, 2 ^ 8 = 256种可能
    unsigned int hashTable[tableSize]; //构建哈希表
    for (unsigned int i = 0; i < tableSize; ++i)
        hashTable[i] = 0;

    const char* pHashKey = pString; //字符串索引/哈希表key值
    //第一次遍历统计字符出现次数
    while (*(pHashKey) != '')
        hashTable[*(pHashKey++)] ++;  //将 ++pHasKey 结合到一句

    pHashKey = pString;
    //第二次遍历寻找出现次数为1的第一个字符
    while (*pHashKey != '')
    {
        if (hashTable[*pHashKey] == 1)
            return *pHashKey;

        ++pHashKey;
    }
    return '';
}
// ====================测试代码====================
void Test(const char* pString, char expected)
{
    if (FirstNotRepeatingChar(pString) == expected)
        printf("Test passed.
");
    else
        printf("Test failed.
");
}

int main(int argc, char* argv[])
{
    // 常规输入测试,存在只出现一次的字符
    Test("google", 'l');

    // 常规输入测试,不存在只出现一次的字符
    Test("aabccdbd", '');

    // 常规输入测试,所有字符都只出现一次
    Test("abcdefg", 'a');

    // 鲁棒性测试,输入nullptr
    Test(nullptr, '');

    return 0;
}
测试代码

分析:确实是简易哈希表。

注意牛客网是返回位置,上述代码是返回字符。

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        
        if (str.length() <= 0)
            return -1;
        
        const int tableSize = 256;
        unsigned int hashTable[tableSize];
        for (unsigned int i = 0; i < tableSize; ++i)
            hashTable[i] = 0;
        
        int hashKey = 0;
        while (str[hashKey] != '')
            hashTable[str[hashKey++]] ++;
        
        hashKey = 0;
        while (str[hashKey] != '')
        {
            if (hashTable[str[hashKey]] == 1)
                return hashKey;
            
            ++hashKey;
        }
        return -1;
    }
};
牛客网提交代码

 

 

 

 

原文地址:https://www.cnblogs.com/ZSY-blog/p/12638169.html