题目描述:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。
Solutions
用 hash 表就可以了:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.s = ''
self.hash = {}
# 返回对应char
def FirstAppearingOnce(self):
# write code here
for c in self.s:
if self.hash[c] == 1:
return c
return '#'
def Insert(self, char):
# write code here
self.s = self.s + char
self.hash[char] = self.hash.get(char, 0) + 1
# 运行时间:36ms
# 占用内存:5624k