字符流中第一个不重复的字符

题目

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。如果当前字符流没有存在出现一次的字符,返回#字符。

思路

用一个128位数组存储每个字符出现的次数,初始为0,每当插入一个字符时,当前字符的计数加1,然后判断当前的计数,如果等于1的话就压入到队列里面去,当要输出第一个只出现一次的字符时,队列里面的元素依次弹出一直到队首元素目前统计出现的次数为1为止。

参考代码

class Solution
{
public:
    Solution()
    {
        memset(cnt, 0, sizeof(cnt));
    }
    //Insert one char from stringstream
    void Insert(char ch)
    {
        cnt[ch]++;
        if (cnt[ch] == 1)
        {
            q.push(ch);
        }
    }
    //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        while (!q.empty() && cnt[q.front()] >= 2) q.pop();
        if (!q.empty()) return q.front();
        else return '#';
    }
private:
    queue<char> q;
    int cnt[128];
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章