字符流中第一个不重复的字符

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

题目描述

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

输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。

思路:

既然想找出现第一次的字符,首先想到的就是hash表中key-val的存储方式,将出现字符的字符(key)与该字符出现的次数构成一个对应关系,方便进行查询。

class Solution
{
public:
  //Insert one char from stringstream
    void Insert(char ch)
    {
        vec.push_back(ch);
         mapdata[ch]++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        vector<char>::iterator it;
        for(it = vec.begin();it != vec.end();it++)
        {
            if(mapdata[*it] == 1)
            {
                return *it;
            }
        }
        return '#';
    }
    map<char,int> mapdata;
    vector<char> vec;

};
原文地址:https://www.cnblogs.com/whiteBear/p/12674111.html