• (剑指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 '#';
        }
    
    };
  • 相关阅读:
    Jquery想说爱你不容易
    关于css
    sass相关实例
    web前端学习之HTML
    web前端学习
    软件工程来换网前端设计
    关于前端开发的相关资料及例子
    四则运算
    自我介绍
    关于读完《软件工程》之后不解的问题
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4703171.html
Copyright © 2020-2023  润新知