题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
#include<iostream>
#include<queue>
using namespace std;
/*
1.创建一个数组,保存字符串中每个元素出现的次数;
2.创建一个队列,将第一次遇到的字符串元素插入队列,其他情况不插入;
3.判断队首元素是否出现了一次,如果是,直接返回,不是的话返回‘#’。
*/
class Solution
{
public:
Solution()
{
for(int i = 0;i < 256;++i)
{
hash[i] = 0;
}
}
void Insert(char ch)
{
hash[ch]++;
if(hash[ch] == 1)
{
FirstAppear.push(hash[ch]);//相同的字符只被插入一次
}
}
char FirstAppearonce()
{
while(!FirstAppear.empty() && hash[FirstAppear.front()] != 1)
FirstAppear.pop();
if(FirstAppear.empty())
return '#';
else
return FirstAppear.front();
}
private:
int hash[256];
queue<char> FirstAppear;
};