面试题50:第一个只出现一次的字符

一、题目

在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出“b”。

二、解法(hashTable)

    思路:为了解决这个问题,可以定义哈希表的KEY是字符,而Value是该字符出现的次数,同时我们还需要从头开始扫面字符串两次,第一次扫描字符串时,每扫描到一个字符,就在哈希表对应项中把次数加1。接下来第二次扫描时,没扫到一个字符,就能在哈希表中得到该字符出现的次数。这样,第一个只出现一次的字符就是符合要求的输出。

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

    const int tableSize = 256;
    unsigned int hashTable[tableSize];
    for(unsigned int i = 0; i < tableSize; ++i)
        hashTable[i] = 0;

    const char* pHashKey = pString;
    while(*(pHashKey) != '\0')
        hashTable[*(pHashKey++)] ++;

    pHashKey = pString;
    while(*pHashKey != '\0')
    {
        if(hashTable[*pHashKey] == 1)
            return *pHashKey;

        pHashKey++;
    }

    return '\0';
}

猜你喜欢

转载自blog.csdn.net/sinat_36161667/article/details/81044452