简体   繁体   English

Stream 中的第一个非重复字符 Python

[英]First Non-Repeating Character In Stream in Python

Here's my original code这是我的原始代码

from collections import OrderedDict
class Solution:
  def __init__(self):
    # Initialize the class.
    self.dic = OrderedDict()

  def read(self, ch):
    # Implement this method here.
    if ch in self.dic:
      self.dic[ch] += 1
    else:
      self.dic[ch] = 1
    self.dic = dict(sorted(self.dic.items(), key=lambda item: item[1]))

  def first_non_repeat(self):
    # Implement this method here.
    if list(self.dic.values())[0] != 1 or not self.dic:
      return None
    else:
      return list(self.dic.keys())[0]

I'd like to find the first non-repeating character in O(1) time at any moment when calling the method, so I use the OrderedDict to trace the character in the stream, However, when the stream are我想在调用该方法的任何时刻在 O(1) 时间内找到第一个非重复字符,所以我使用 OrderedDict 来跟踪 stream 中的字符,但是,当 stream 是

['a', 'b', 'c', 'b', 'a', 'd', 'c', 'd', 'a', 'e']

the output should be output 应该是

['a', 'a', 'a', 'a', 'c', 'c', 'd', None, None, 'e']

However, Mine is然而,我的是

['a', 'a', 'a', 'a', 'c', 'c', None, None, None, None]

Could anyone help me to figure out where I'm wrong?谁能帮我弄清楚我哪里错了? Thanks谢谢

Is this something you are looking for?这是您要找的东西吗?

lst=['a', 'b', 'c', 'b', 'a', 'd', 'c', 'd', 'a', 'e']
d={x : lst.count(x) for x in lst}
min(d,key=d.get)

This will return e这将返回 e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM