面试题55:字符流中第一个不重复的字符

来源:互联网 发布:python运算符 编辑:程序博客网 时间:2024/06/05 17:38
       题目:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。 
输出描述::如果当前字符流没有存在出现一次的字符,返回#字符。
这种题目我一般是采用一个map去记它的计数,书上是采用一个数组去计数,采用数组的好处是,在字符很多很多的情况下,优势明显,但是我编写的程序没有在牛客上通过,自己运行那个没过的测试例子却通过了,我也不知道为啥没通过。
class Solution{public:  //Insert one char from stringstream    Solution():index(0)    {        int i;        for(i=0; i<256; i++)            occurrence[i] = -1;    }    void Insert(char ch)    {         if(occurrence[ch] == -1)             occurrence[ch] = index;         else if(occurrence[ch] >= 0)             occurrence[ch] = -2;         index++;    }  //return the first appearence once char in current stringstream    char FirstAppearingOnce()    {        index=INT_MAX;        char ch='#';        int i;        for(i=0; i< 256; i++)        {            if(occurrence[i] >= 0 && occurrence[i] < index)            {                index = occurrence[i];                ch = (char)i;            }                  }        return ch;    }private:    int occurrence[256];    int index;};


0 0
原创粉丝点击