题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路
《剑指offer》P269
考虑使用一个有序字典OrderedDict()
来保存每个字符及其出现的次数,字典本质是一个哈希表,存取的时间复杂度都是O(1)
。
每次获取第一次出现一次的字符时,遍历有序字典,找到第一个次数为1词的字符。
整体时间复杂度为O(N)
code
# -*- coding:utf-8 -*-
import collections
class Solution:
# 返回对应char
def __init__(self):
self.str = collections.OrderedDict()
def FirstAppearingOnce(self):
# write code here
for c in self.str:
if self.str[c] == 1:
return c
return '#'
def Insert(self, char):
# write code here
if char in self.str:
self.str[char] += 1
else:
self.str[char] = 1