第一个只出现一次的字符
文章目录
//找到字符流中第一个只出现一次的字符
//构建哈希表,用字符的ASCII码做下标,数值就是该字符在字符流中的位置,如果出现多次,那么这个数值就改成一个负值-2
#include <iostream>
#include<limits>
using namespace std;
class CharStatistics{
public:
CharStatistics():index(0)//下标初始值0
{
for(int i=0;i<256;i++)
occurence[i]=-1;//初始化哈希表
}
void Insert(char ch){
if(occurence[ch]==-1)
occurence[ch]=index;
else if(occurence[ch]>=0)
occurence[ch]=-2;//不止出现一次
index++;
}
char FirstAppearingOnce(){
char ch='\0';
int minIndex=numeric_limits<int>::max();//int可以表示的最大值
for(int i=0;i<256;i++){
if(occurence[i]>=0 && occurence[i]<minIndex){//第一个只出现一次
minIndex=occurence[i];
ch=(char)i;
}
}
return ch;
}
private:
//occurence[i]:A character with ASCII value i;
//occurence[i]=-1: the character has not been found;
//occurence[i]=-2: the character has been found with multiple times
//occurence[i]>=0: the character has been found once
int occurence[256];//ASCII码有 256 个,一个字节8位
int index;
};
int main()
{
CharStatistics test;
test.Insert('g');
cout<<test.FirstAppearingOnce();
cout<<endl;
test.Insert('o');
test.Insert('o');
test.Insert('g');
test.Insert('l');
test.Insert('e');
cout<<test.FirstAppearingOnce();
cout<<endl;
return 0;
}