簡體   English   中英

Stream 中的第一個非重復字符 Python

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

這是我的原始代碼

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]

我想在調用該方法的任何時刻在 O(1) 時間內找到第一個非重復字符,所以我使用 OrderedDict 來跟蹤 stream 中的字符,但是,當 stream 是

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

output 應該是

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

然而,我的是

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

誰能幫我弄清楚我哪里錯了? 謝謝

這是您要找的東西嗎?

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)

這將返回 e

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM