剑指offer 字符流中第一个不重复的字符

来源:互联网 发布:第三方网络平台模式 编辑:程序博客网 时间:2024/06/16 18:44

题目描述

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

思路:因为字符只出现一次,称为字符流,所以有两种方法,1. 将输入流的字符保存下来,然后统计每个字符的次数,然后返回只出现第一次的位置。

2. 使用hash table处理。


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






0 0
原创粉丝点击