美文网首页
字符流中第一个不重复的字符

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

作者: hades2013 | 来源:发表于2018-10-09 15:53 被阅读0次

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

方法一:

class Solution {
public:
    Solution(): index(0) {
        for (int i = 0; i < 256; ++i) {
            occurrence[i] = -1;
        }
    }
  //Insert one char from stringstream
    void Insert(char ch) {
        if (occurrence[ch] == -1) {
            occurrence[ch] = index;
        }
        else {
            occurrence[ch] = -2;
        }
        ++index;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce() {
        char ch = '#';
        int minIndex = INT_MAX;
        for (int i = 0; i < 256; ++i) {
            if (occurrence[i] >= 0 && occurrence[i] < minIndex) {
                minIndex = occurrence[i];
                ch = i;
            }
        }
        return ch;
    }
private:
    int occurrence[256];
    int index;
};

方法二:

class Solution
{
public:
  //Insert one char from stringstream
    void Insert(char ch)
    {
        ++hashArray[ch-'\0'];
        if( hashArray[ch-'\0'] == 1){
            data.push_back(ch);
        }
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        while( !data.empty() && hashArray[data.front()] >= 2 ){
            data.pop_front();
        }
        if( data.empty() )
            return '#';
        return data.front();
    
    }

private:
    unsigned char hashArray[128];
    deque<char> data;

};

相关文章

  • JZ-054-字符流中第一个不重复的字符

    字符流中第一个不重复的字符 题目描述 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读...

  • 剑指offer | 字符串中第一个不重复的字符

    字符串中第一个不重复的字符 请实现一个函数用来找出字符流中第一个只出现一次的字符 示例输入:google输出:l ...

  • 46-50题

    46、字符流中第一个不重复的字符用字典计数,然后遍历列表,得到第一个value为1的字符 47、替换空格可以直接用...

  • 剑指offer第二周

    正则表达式link 表示数值的字符串 做的好像有点麻烦了,带有小数和不带小数的分别判断 字符流中第一个不重复的字符...

  • 剑指offer|51-60题解题思路及代码(Java版)

    剑指offer51到60题总览: 构建乘积数组 正则表达式匹配 表示数值的字符串 字符流中第一个不重复的字符 链表...

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

    题目描述请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个...

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

    题目描述   请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,...

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

    请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一...

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

    实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次...

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

    题目描述:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一...

网友评论

      本文标题:字符流中第一个不重复的字符

      本文链接:https://www.haomeiwen.com/subject/sqfyaftx.html