第54题 字符流中第一个不重复的字符
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
class Solution
{
public:
//Insert one char from stringstream
unordered_map<char,int> m;
queue<char> q;
void Insert(char ch)
{
if(m.find(ch) == m.end()){
q.push(ch);
}
++m[ch];
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
while(!q.empty()){
char c = q.front();
if(m[c]==1){
return c;
}else{
q.pop();
}
}
return '#';
}
};
该问题涉及字符流处理,使用一个哈希映射和队列来追踪字符出现的频率。当插入字符时,如果字符不在映射中,则将其加入队列;若已存在,则更新计数。`FirstAppearingOnce`方法会检查队列中的字符,返回首次出现一次的字符或默认字符'#'。
172万+

被折叠的 条评论
为什么被折叠?



