您的位置:首页 > 其它

查找字符串中出现一次且第一次出现的字符

2016-08-09 20:45 225 查看
原理:利用哈希表的算法进行查找,创建一个能存储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;

}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: