剑指offer刷题笔记54(python)
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
思路1
利用一个队列和字典来实现。
代码1
class Solution:
def __init__(self
):
self
.memory
= dict()
self
.queue
= []
def FirstAppearingOnce(self
):
while len(self
.queue
) and self
.memory
[self
.queue
[0]]>1:
self
.queue
.pop
(0)
return self
.queue
[0] if len(self
.queue
) else '#'
def Insert(self
, char
):
if char
not in self
.memory
:
self
.memory
[char
]=0
self
.memory
[char
]+=1
if self
.memory
[char
]==1:
self
.queue
.append
(char
)
思路2
由于ASCII码有128位,扩展的ASCII码有256位,字符最多有256个(不考虑中文字符),因此我们可以利用一个长度为256的数组来实现一个类似于字典的功能。 数组的各个位置(0-256)就相当于字符的ASCII码。数组的值初始化为-1, 表示第一次读入。数组的值不为-1且大于等于0时,表示不是第一次读入,修改当前的值为-2,在读入的时候,如果碰见-2,就不再进行处理了。同时要设置一个读入顺序的指标,当元素不为-2时,将这个指标赋值给不等于-2的元素。在读取的时候要读取数组元素值不大于等于0的最小的元素,并返回这个位置所代表的字符。
代码2
class Solution:
def __init__(self
):
self
. occurence
= [-1 for i
in range(256)]
self
.index
= 0
def FirstAppearingOnce(self
):
minValue
= 10000
minIndex
= -1
for i
in range(256):
if self
. occurence
[i
] >= 0:
if self
. occurence
[i
] < minValue
:
minValue
= self
. occurence
[i
]
minIndex
= i
if minIndex
>= 0:
return chr(minIndex
)
else:
return '#'
def Insert(self
, char
):
if self
. occurence
[ord(char
)] == -1:
self
. occurence
[ord(char
)] = self
.index
else:
self
. occurence
[ord(char
)] = -2
self
.index
+= 1