简体   繁体   中英

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

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

the output should be

['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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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