题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
/*思路:由于字符只能从字符流中一个一个读取,可以定义一个哈希表来保存字符在字符流中的位置
用字符的ASCII码作为哈希表的键值,字符对应的位置作为哈希表的值。
初始哈希表值全为-1,当字符第一次从字符流中读取出来时,把它的位置保存在哈希表中,当再一次被读取出来时,就可以被忽略,此时哈希表值改为-2;
找第一个不重复的字符,只需遍历整个哈希表,找到最小的大于等于0的值对应的字符即可*/
class Solution
{
public:
Solution() :index(0) {
for (int i = 0; i < 256; ++i)
occurrence[i] = -1; //初始化数组
}
//Insert one char from stringstream
void Insert(char ch)
{
if (occurrence[ch] == -1) // -1 表示该字符还没有出现
occurrence[ch] = index;
else if (occurrence[ch] >= 0) // >=0 表示该字符出现了一次
occurrence[ch] = -2;
++index;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
char ch = '#'; //不存在只出现一次的字符时,返回#
int minIndex = numeric_limits<int>::max(); //返回编译器允许的int型数最大值
for (int i = 0; i < 256; ++i)
{
if (occurrence[i] >= 0 && occurrence[i] < minIndex)
{
ch = (char)i; //找到第一个不重复的字符
minIndex = occurrence[i];
}
}
return ch;
}
private:
int occurrence[256]; //构建 Hash 表
int index; //记录字符在字符流中的位置
};