剑指offer50拓展:字符流中第一个不重复的字符

题目描述

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

输出描述:

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

思路:本题目是第一个只出现一次字符题目的拓展,不同的是,输入是字符流,需要我们先通过Insert函数把字符流保存下来,
然后去FirstAppearingOnce函数中比较判断,返回第一个只出现一次的字符

这里还是使用了50题剑指offer书上的思路,利用一个256的数组来存储字符出现的次数。使用vector<char>来记录输入的字符串,方便操作。
class Solution
{
public:
    int array[256] = {0};
    vector<char> str;
  //Insert one char from stringstream
    void Insert(char ch)
    {
        array[ch]++;
        str.push_back(ch);
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        for(vector<char>::iterator it= str.begin();it!=str.end();it++){
            if(array[*it]==1)
                return *it;
        }
        return '#';
    }

};
原文地址:https://www.cnblogs.com/ttzz/p/13805806.html