字符流中第一个不重复的字符
时间限制:1秒 空间限制:32768K
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
如果当前字符流没有存在出现一次的字符,返回#字符。
题目分析
ASCII码表中一共包含128个字符,因此我们可以定义一个包含128个元素的数组hashArray,同时定义一个存放第一个一共出现1次的字符的队列data。
当插入一个字符ch时,hashArray[ch]++。如果ch为第一次出现,则插入队尾。
当查找第一个出现的字符时,如果队列中第一个字符只出现一次,则返回第一个字符,否则弹出队列,查找下一个,直到队列为空,或者找到第一个只出现一次的字符。代码实现如下:
代码实现
class Solution
{
private:
unsigned char hashArray[128];
deque<char>data;
public:
//Insert one char from stringstream
void Insert(char ch)
{
hashArray[ch]++;
if (hashArray[ch] == 1)
{
data.push_back(ch);
}
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
while (data.size() != 0 && hashArray[data.front()] != 1)
{
data.pop_front();
}
if(data.size() == 0)
return '#';
return data.front();
}
};