算法题目---第一个只出现一次的字符

来源:互联网 发布:大作家软件好用吗 编辑:程序博客网 时间:2024/05/22 06:22

在字符中找出第一个只出现一次的字符。

如输入"abaccdeff",则输出'b'



char FirstNotRepeat(char* pString)

{
    if(pString == NULL)
        return '\0';
    
    const int tableSize = 256;
    unsigned int hashTable[tableSize];
    for(unsigned int i = 0; i < tableSize;++i)
        hashTable[i] = 0;
    
    char* pHashKey = pString;
    while(*(pHashKey) != '\0')
        hashTable[*(pHashKey++)]++;
    
    pHashKey = pString;
    while(*pHashKey != '\0')
    {
        if(hashTable[*pHashKey] == 1)
            return *pHashKey;
        pHashKey++;
    }

    return '\0';
}

void Test(char* pString, char expected)
{
    if(FirstNotRepeat(pString) == expected)
        printf("Test passed.\n");
    else
        printf("Test failed.\n");
}

int main()
{
      Test("google", 'l');
        Test("aabccdbd", '\0');
         Test("abcdefg", 'a');
      Test(NULL, '\0');

    return 0;
}


原创粉丝点击