第一个只出现一次的字符

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

思路:我们可以把数组当做一个简单的哈希表来用,把每个字母的ASCII码值作为在数组中的位置(下标),数组中存储的是该字符出现的次数。这样我们就创建了一个以字符ASCII码为健值的哈希表。

具体代码如下:

 1 char FirstNotRepeatingChar(char* pstr)
 2 {
 3     if (pstr == NULL)
 4     {
 5         return '';
 6     }
 7     const int HashTableSize = 256 ;
 8     int HashTable[HashTableSize] ;
 9 
10     for (int i = 0 ; i < HashTableSize ; i++)
11     {
12         HashTable[i] = 0 ;
13     }
14     char* pHashKey = pstr ;
15     while ( *pHashKey != '')
16     {
17         HashTable[*(pHashKey++)]++ ;
18     }
19     pHashKey = pstr ;
20     while (*pHashKey != '')
21     {
22         if (HashTable[*pHashKey] == 1)
23         {
24             return *pHashKey ;
25         }
26         pHashKey++ ;
27     }
28     return '';
29 }
原文地址:https://www.cnblogs.com/csxcode/p/3728594.html