题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
思路
class Solution:
def __init__(self):
self.s=''
self.dict={}
def FirstAppearingOnce(self):
# write code here
for i in self.s: #遍历字符串s中的字符
if self.dict[i]==1: #如果某个字符对应的计数为1,则返回该字符
return i
return '#' #在所有字符遍历完后,进行判断
def Insert(self, char):
# write code here
self.s=self.s+char #从字符流中读入字符到字符串s中
if char in self.dict:
self.dict[char]=self.dict[char]+1 #如果读入的字符在字符串中已存在,在字典中对应的字符计数加一
else:
self.dict[char]=1 #如果读入的字符在字符串中不存在,则字典中对应的字符计数为一(即新增了一个新的字符)
测试用例
if __name__ == '__main__':
s = Solution()
ss = 'google'
for i in list(ss):
s.Insert(i)
print(s.FirstAppearingOnce())
输出结果