(剑指Offer)面试题55:字符流中第一个不重复的字符

题目:

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

思路:

字符流:像流水一样的字符,一去不复返,意味着只能访问一次。

方法1:将字符流保存起来

通过哈希表统计字符流中每个字符出现的次数,顺便将字符流保存在string中,然后再遍历string,从哈希表中找到第一个出现一次的字符;

方法2:哈希表特殊处理

同样通过哈希表来统计字符流中每个字符,不过不是统计次数,而是保存位置,哈希表初始化每个键值对应的value均为-1,如果字符出现一次,则value等于该字符的下标,如果字符出现两次,则value等于-2;这样遍历哈希表时,第一个value大于0的字符就是第一个出现一次的字符;

代码:

参考下面的在线测试代码

在线测试OJ:

http://www.nowcoder.com/books/coding-interviews/00de97733b8e4f97a3fb5c680ee10720?rp=3

AC代码:

方法1:

class Solution
{
private:
    string str;
    int count[256]={0};
public:
  //Insert one char from stringstream
    void Insert(char ch)
    {
        str+=ch;
        count[ch]++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
    	int len=str.size();
        for(int i=0;i<len;i++){
            if(count[str[i]]==1)
                return str[i];
        }
        return '#';
    }

};

方法2:(暂未AC,原因不详)

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

};
posted @ 2015-08-04 21:24  AndyJee  阅读(3747)  评论(0编辑  收藏  举报