題目描述
請實現一個函數用來找出字符流中第一個只出現一次的字符。例如,當從字符流中只讀出前兩個字符"go"時,第一個只出現一次的字符是"g"。當從該字符流中讀出前六個字符“google"時,第一個只出現一次的字符是"l"。
輸出描述:
如果當前字符流沒有存在出現一次的字符,返回#字符。
from collections import defaultdict
class Solution:
"""
雖然是要從字符流中獲取首個第一次出現的字符,但是本質上和在字符串中做同樣的事沒有什麼區別,
唯一的區別就在於要記錄字符流的輸入順序。
"""
def __init__(self):
self.char_count = defaultdict(int)
self.sequence = ''
def FirstAppearingOnce(self):
# 遍歷字符流的輸入,然後找出第一個只出現一次的字符
for c in self.sequence:
if self.char_count[c] == 1:
return c
return '#'
def Insert(self, char):
for c in char:
self.sequence += c
self.char_count[c] += 1