1、题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。
例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是’g’。
当从该字符流中读出前六个字符”google”时,第一个只出现一次的字符是’l’。
如果当前字符流没有存在出现一次的字符,返回#字符。
样例
输入:"google"
输出:"ggg#ll"
- 解释:每当字符流读入一个字符,就进行一次判断并输出当前的第一个只出现一次的字符。
2、问题描述:
- 字符流,每次输入都要判断一次,当前只出现一次的第一个字符。
3、问题关键:
- 可以建立一个队列,保证队头的元素是只出现一次的,否则就做出队操作。
- 便于查找队头元素是否一次,把队列元素用hash表保存。
4、C++代码:
class Solution{
public:
//Insert one char from stringstream
unordered_map<char, int> m;
queue<char> q;
void insert(char ch){
m[ch] ++;
if (m[q.front()] > 1)
while(q.size() && m[q.front()] > 1) q.pop();//直到队头元素只出现一次,或者队列为空。
else
q.push(ch);
}
//return the first appearence once char in current stringstream
char firstAppearingOnce(){
if (q.empty()) return '#';
else
return q.front();
}
};
网友评论