【剑指 offer】字符流中第一个不重复的字符

题目描述:

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

思路:

字符流:像流水一样的字符,一去不复返,意味着只能访问一次。
在插入字符时,记录当前字符出现的次数,可以用长度为128的数组标记,如果当前字符出现次数为1,入队。要取出当前字符流中第一个只出现一次的字符时,把队首的出现次数>1的字符pop掉,队列不为空时返回队首字符。

代码:

class Solution
{
private:
    queue<char> data;
    unsigned cnt[128];

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()] > 1) {
            data.pop();
        }
        if (data.empty()) return '#';
        return data.front();
    }
};

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/89478806
今日推荐