題目描述
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符"go"時,第一個只出現一次的字符是"g"。當從該字符流中讀出前六個字符“google"時,第一個只出現一次的字符是"l"。如果當前字符流沒有存在出現一次的字符,返回#字符。
思路
和前面的那道字符串中只出現一次的字符相似而不相同,前面那道是固定長度字符串,而本題是字符流,也就是會增長的,每次字符串多一個字符,就要重新判斷是哪個只出現一次的字符
因為牛客網里劍指offer的python只有2.7,沒有3.0以上的版本,而python2.7的字典遍歷通常不是有序的(python3通常有序),所以只能再借助一個列表來存儲全部字符串,遍歷字符串從而尋找
解答
class Solution: # 返回對應char def __init__(self): self.charDict = {}#存放字符和對應的數量 self.charlist = []#存放字符 def FirstAppearingOnce(self): # write code here for key in self.charlist: if self.charDict[key]==1: return key return '#' def Insert(self, char): # write code here self.charDict[char]=1 if char not in self.charDict else self.charDict[char]+1 self.charlist.append(char)
其實再想一下,把字典去掉也完全可以啊,這跟那道固定長度的只出現一次字符串沒有本質的區別
class Solution: # 返回對應char def __init__(self): self.charlist = [] def FirstAppearingOnce(self): # write code here for key in self.charlist: if self.charlist.count(key)==1: return key return '#' def Insert(self, char): # write code here self.charlist.append(char)