题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
总结牛客上一位大神的方法:
1.用一个128大小的数组统计每个字符出现的个数。
2.在队列中存入第一次遇到的字符,插入队列,其他情况不处理
3.题目是求解第一次遇到的字符,即判断队列首元素是否只出现一次,是则直接返回,否则删除队列首元素,判断下一个
代码如下
class Solution
{
public:
//Insert one char from stringstream
void Insert(char ch)
{
++cnt[ch-'\0'];
if(cnt[ch-'\0'] == 1)
data.push(ch);
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
while(!data.empty() && cnt[data.front()] >=2 )
{
data.pop();
}
if(data.empty())
return '#';
return data.front();
}
Solution()
{
memset(cnt, 0, sizeof(cnt));
}
public:
queue<char> data;
unsigned cnt[128];
};