题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。
例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是’g’。
当从该字符流中读出前六个字符”google”时,第一个只出现一次的字符是’l’。
如果当前字符流没有存在出现一次的字符,返回#字符。
样例
输入:"google"
输出:"ggg#ll"
解释:每当字符流读入一个字符,就进行一次判断并输出当前的第一个只出现一次的字符。
问题分析
insert函数:先将字符c在哈希map中的次数加1,然后将该字符push进队列中。然后循环判断队头,如果队列非空并且队头的字符在哈希map中的出现次数大于1,那么将对头弹出。firstAppearingOnce函数:如果队列非空,那么返回队列的头元素,如果为空则返回'#'。
代码实现
class Solution{
private:
unordered_map<char, int> umap;
queue<char> q;
public:
//Insert one char from stringstream
void insert(char ch){
++umap[ch];
q.push(ch);
while(q.size() && umap[q.front()] > 1)
q.pop();
}
//return the first appearence once char in current stringstream
char firstAppearingOnce(){
return q.empty() ? '#' : q.front();
}
};