友情提醒:ASCII碼使用指定的8位二進制數組合來表示256種可能的字符。
解:
由於字符(char)是一個長度爲8的數據類型,因此總共有可能256 種可能。於是我們創建一個長度爲256的數組,每個字母根據其ASCII碼值作爲數組的下標對應數組的對應項,而數組中存儲的是每個字符對應的次數。這樣我們就創建了一個大小爲256,以字符ASCII碼爲鍵值的哈希表。(並不僅限於英文字符,所以這裏要考慮256種可能)。我們第一遍掃描這個數組時,每碰到一個字符,在哈希表中找到對應的項並把出現的次數增加一次。這樣在進行第二次掃描時,就能直接從哈希表中得到每個字符出現的次數了。
char FirstNotRepeatingChar(char* pString)
{
// invalid input
if(!pString)
return 0;
// get a hash table, and initialize it
const int tableSize = 256;
unsigned int hashTable[tableSize];
for(unsigned int i = 0; i < tableSize; ++ i)
hashTable = 0;
// get the how many times each char appears in the string
char* pHashKey = pString;
while(*(pHashKey) != '\0')
hashTable[*(pHashKey++)] ++; //以字符的數值大小爲哈希數組的下標
// find the first char which appears only once in a string
pHashKey = pString;
while(*pHashKey != '\0')
{
if(hashTable[*pHashKey] == 1)
return *pHashKey;
pHashKey++;
}
// if the string is empty
// or every char in the string appears at least twice
return 0;
}