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

前面有一道题跟这个很类似,第35题。有了那个的经验这个就很好做了。区别是这个需要做的是一个字符流的只出现一次的字符,也就是字符串的情况是动态变化的。

有两个数据结构,一个是string类型的用来存储当前的字符流,还有一个用数组表示的哈希表来存储各个字符出现的次数。找第一个只出现一次的字符就是找哈希表中第一个值为1的字符。

 1 class Solution
 2 {
 3 public:
 4     Solution()//构造函数给私有成员赋初值
 5     {
 6         str = "";
 7         for (int i = 0; i < 256; i++)
 8         {
 9             count[i] = 0;
10         }
11     }
12     //Insert one char from stringstream
13     void Insert(char ch)
14     {
15         str += ch;
16         count[int (ch)]++;
17     }
18     //return the first appearence once char in current stringstream
19     char FirstAppearingOnce()
20     {
21         int len = str.size();
22         for (int i = 0; i < len; i++)
23         {
24             //cout << int(str[i]) << endl;
25             if (count[int(str[i])] == 1)
26                 return char(str[i]);
27         }
28         return '#';
29     }
30 private:
31     string str;
32     int count[256];
33 };

 

posted @ 2019-07-25 14:38  妮妮熊  阅读(144)  评论(0编辑  收藏  举报