请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。
思路:使用哈希表。
1.可以用哈希表存储每个字符出现的次数,找到第一个次数为1的字符。如何找到第一个?可以遍历字符串,也可以利用队列。
2.可以用哈希表存储每个字符所在的位置,如果没有出现记为-1,出现的次数大于1次记为-2,找出除了-1、-2以外位置值最小的字符。
# -*- coding:utf-8 -*-
class Solution:
# 返回对应char
def __init__(self):
self.hash_map = [-1 for i in range(256)]
self.index = 0
def FirstAppearingOnce(self):
# write code here
min_index = 255
ch = '#'
for j in range(256):
if self.hash_map[j] >= 0 and self.hash_map[j] < min_index:
ch = chr(j)
min_index = self.hash_map[j]
return ch
def Insert(self, char):
# write code here
if self.hash_map[ord(char)] == -1:
self.hash_map[ord(char)] = self.index
else:
self.hash_map[ord(char)] = -2
self.index += 1