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

题目描述:

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

输出描述:

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

思路分析:

在插入操作中利用hash表,保存每个输入的字符出现的次数。再遍历当前的字符流,查询对应字符的hash表,为1即为所求的字符。时间空间复杂度都为O(n)。

代码:

 1 class Solution
 2 {
 3 public:
 4     string str;
 5     char hash[256]={0};
 6   //Insert one char from stringstream
 7     void Insert(char ch)
 8     {
 9         str = str+ch;
10         hash[ch]++;
11     }
12   //return the first appearence once char in current stringstream
13     char FirstAppearingOnce()
14     {
15         int len = str.size();
16         for(int i=0; i<len; i++)
17         {
18             if(hash[str[i]]==1)
19                 return str[i];
20         }
21         return '#';
22     }
23 
24 };
原文地址:https://www.cnblogs.com/LJ-LJ/p/11070651.html