字符流中第一个不重复的字符

天大地大妈咪最大 提交于 2019-12-06 03:45:48

问题:

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。如果当前字符流没有存在出现一次的字符,返回#字符。

input:

字符流

output:

第一个只出现一次的字符

解题思路:

使用字典存储字符流中的字符以及每个字符出现的次数.

但为了获得 第一个 出现一次的字符,需要这个字典有序,或者能得到字符流的输入序列,因此有以下几种方法来解决:

  1. python3 中字典有序

  2. 使用list保存字符流内容,查找 第一个 时,就按list中顺序遍历

  3. 使用string 保存字符流内容, 查找 第一个 时,就按string中顺序遍历

    另外一个获得字典的方法是:

  4. 先根据字符流得到list,这个list是有序的,之后使用 collect中的counter方法 计算字符出现的次数得到字典,最后按list顺序遍历查找.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
from collections import Counterclass Solution:    def __init__(self): 大专栏  字符流中第一个不重复的字符        self.dictChar = {}        self.charList = []        self.s = ''    # 这样直接按字典进行遍历的,存在问题是字典在py2.7中无序,因此只能在py3中使用这种方法    # 返回对应char    def FirstAppearingOnce(self):        # write code here        for key in self.dictChar:            if self.dictChar[key] == 1:                return key        return '#'    def Insert(self, char):        # write code here        self.dictChar[char] = 1 if char not in self.dictChar else self.dictChar[char] + 1    # 用一个list来保存每次输入的顺序    def FirstAppearingOnce1(self):        # write code here        for key in self.charList:            if self.dictChar[key] == 1:                return key        return '#'    def Insert1(self, char):        # write code here        self.dictChar[char] = 1 if char not in self.dictChar else self.dictChar[char] + 1        self.charList.append(char)    # 用一个字符串保存每次输入的顺序    def FirstAppearingOnce2(self):        # write code here        for key in self.s:            if self.dictChar[key] == 1:                return key        return '#'    def Insert2(self, char):        # write code here        self.dictChar[char] = 1 if char not in self.dictChar else self.dictChar[char] + 1        self.s += char    # counter()字典可以不用自己建立    def FirstAppearingOnce3(self):        # write code here        charDict = Counter(self.charList)        for key in self.charList:            if charDict[key] == 1:                return key        return '#'    def Insert3(self, char):        # write code here        self.charList.append(char)def main():    solution = Solution()    CharList = 'google'    # 进行字符流操作    for char in CharList:        solution.Insert3(char)        print (solution.FirstAppearingOnce3())if __name__ == "__main__":    main()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!