第一个只出现一次的字符(Hash)

来源:互联网 发布:串口监控软件 编辑:程序博客网 时间:2024/05/27 20:21
#include<iostream>#include<stdlib.h>using namespace std;//题目要求:在字符串中找出第一个只出现一次的字符,如输入"abaccdeff",则输出b。//传统方法的时间复杂度为o(n^2)//现在我们要用o(n)的方法来解决这个问题//运用hash表,用key代表字符,value代表字符出现的次数char Firstnotrepeatingchar(char *pString){if(pString == NULL) return '\0';const int tableSize = 256;//2的8次方,主要是一个字符占8个字unsigned int hashTable[tableSize];for(unsigned int 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 = "abscdadweefg";char result  = Firstnotrepeatingchar(str);cout<<result<<endl;return 1;} 

0 0
原创粉丝点击