第一个只出现一次的字符

来源:互联网 发布:九九乘法表java编程 编辑:程序博客网 时间:2024/05/16 07:35

题目描述:

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

解决办法:

字符是一个长度为8的数据类型,因此共有256种可能,于是我们创建一个长度为256的数组,每个字母根据其ASCLL码值作为数组的下标对应数组的一个数字,而数组中存储的是每个字符出现的次数。这样我们就创建了一个大小为256,以字符ASCLL码作为键值的哈希表。

代码实现:

#include <stdio.h>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')//用字符的ascll码作为数组下标的索引(键)存储每个字符出现的次数hashTable[*(pHashKey++)]++;pHashKey = pString;while((*pHashKey) != '\0'){if(hashTable[*pHashKey] == 1)return *pHashKey;pHashKey++;}return '\0';}int main(){char* pString = "abaccdeff";char result = FirstNotRepeatingChar(pString);printf("%c\n",result);return 0;}





0 0
原创粉丝点击