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

题目描述

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

输出描述:

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


提交链接:点击


思路:
  由于是统计字符及字符出现的次数,因此想到了key-value。构建一个hash表,key为字符,value为出现的次数。时间复杂度O(n),空间复杂度O(n)

代码:
class Solution
{
public:
  //Insert one char from stringstream
    string s;
    char str[256]={0};
    void Insert(char ch)
    {
         s+=ch;
         str[ch]++;
    }
  //return the first appearence once char in current stringstream
    char FirstAppearingOnce()
    {
        int size=s.length();
        for(int i=0;i<size;i++){
            if(str[s[i]]==1){  //遍历出现第一次的字符
                return s[i];
            }
        }
        return '#';
    }
};
原文地址:https://www.cnblogs.com/logo-88/p/10149650.html