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

题目描述

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

输出描述:

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


法1:
建立一个长度256的数组,当作字典

 1 # -*- coding:utf-8 -*-
 2 class Solution():
 3     # 返回对应char
 4     def __init__(self):
 5         self.s=""
 6         self.d = [0]*256
 7     def FirstAppearingOnce(self):
 8         for item in (list(self.s)):
 9             if(self.d[ord(item)]==1):
10                 return item
11         return '#'
12     def Insert(self, char):
13         self.d[ord(char)]+=1
14         self.s+=char


法2:
python 内置函数

 1 # -*- coding:utf-8 -*-
 2 class Solution():
 3     # 返回对应char
 4     def __init__(self):
 5         self.s=""
 6     def FirstAppearingOnce(self):
 7         res = list(filter(lambda x:self.s.count(x)==1,self.s))
 8         return res[0] if res else '#'
 9     def Insert(self, char):
10         self.s+=char

c++:20810729

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