原理:利用哈希表的算法进行查找,创建一个能存储256个数的数组,第一次对出现的字符进行统计,第二次查找出现一次的字符并返回.
#include<stdio.h>
#include<stdlib.h>char FirstNotRepeatingChar(char *pString)
{
if (pString == NULL)
{
return '\0';
}
const int tableSize = 256;
unsigned int hashTable[tableSize];
for (unsigned 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';
}
int main()
{
char *str = "abcde.fghabcdefdsdsfdsada";
char c = FirstNotRepeatingChar(str);
printf("%c", c);
system("pause");
return 0;
}
运行结果: