【剑指offer-解题系列(54)】字符流中第一个不重复的字符

来源:互联网 发布:新津知艺术馆 编辑:程序博客网 时间:2024/06/06 07:02

题目描述

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

分析

 采用频率统计的方法,以及第一个出现位置记录的方法,使用两个数组 times[] , first_show[] 来进行记录就可以了

代码实现

    Solution(){

        pos = 0;
        for(int i =0 ;i<256;i++)
            times[i]=0;
        for(int i =0 ;i<256;i++)
            first_show[i]=-1;
    }
  //Insert one char from stringstream
    void Insert(char ch)
    {
        times[ch]++;
        if(first_show[ch]==-1)
        first_show[ch]=pos;
        pos++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        int c =-1;
        long minPos= LONG_MAX;
        for(int i =0 ;i<256;i++){
            if(first_show[i]!=-1 && times[i]==1 && minPos>first_show[i]){
                minPos= first_show[i];
                c= i;
            }
        }
        if(c<0)
            return '#';
        else
        return char(c);
    }


    long long pos;
    long long times[256];
    long long first_show[256];
阅读全文
0 0
原创粉丝点击