剑指offer-面试题35:第一个只出现一次的字符

题目:在字符串中找出第一个只出现一次的字符。如输入“abaccdeff",则输出'b'。

思路:这道题目不难,遍历一遍统计每个字符出现的次数就完了。作者用的是哈希表,因为只需要统计次数,而且字符只有256中,可以用一个大小为256的数组实现。自己用STL里的multimap容器也实现了,道理完全一样。

//哈希表实现输出第一个只出现一次的字符
char FirstNotRepeatingChar(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';
}

//multimap实现输出第一个只出现一次的字符
char FirstNotRepeatingChar(char* pString)
{
	if(pString == NULL)
		return '\0';
		
	multimap<char, int> char_count;
	for(char* p = pString; *p != '\0'; ++p)
		char_count.insert({*p,1});
	char* key = pString;
	while(*key != '\0')
	{
		if(char_count.count(*key) == 1)
			return *key;
		++key;
	}
	
	return '\0';
}


你可能感兴趣的:(剑指offer-面试题35:第一个只出现一次的字符)