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

题目链接:字符流中第一个不重复的字符

 

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

 

题解:开一个数组存储字符出现的次数,然后遍历字符串,找到出现一次的字符。

 

代码:

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