剑指offer:字符流中第一个不重复的字符(Python)

题目描述

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

输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。

解题思路

用字典(Java中的HashMap结构)来做。字典中的键值对中,键key存储字符;值value存储字符出现的次数。

charDict = {}
def FirstAppearingOnce(self):
    for key in self.charDict:
        if self.charDict[key] == 1:
            return key
    return '#'

def Insert(self, char):
    self.charDict[char] = 1 if char not in self.charDict else self.charDict[char]+1

但上述代码只能用于Python3。虽说Python中字典序为无序,但默认情况下,Python3中的字典序为“顺序”,但Python2中存储字典的算法和Python3中不同,遍历字典键值对时的顺序亦不同。

改进的思路是用列表存储字符流中的顺序,之后以列表中存入的字符流顺序寻找第一个不重复的字符。但此法依旧只适用于Python3..

charDict = {}
list = []
def FirstAppearingOnce(self):
    for key in self.list:
        if self.charDict[key] == 1:
            return key
    return '#'

def Insert(self, char):
    self.charDict[char] = 1 if char not in self.charDict else self.charDict[char]+1
    self.list.append(char)

用字符串来存储字符流的顺序,适用于Python2,但不适用Python3..

charDict = {}
s = ""
def FirstAppearingOnce(self):
    for key in self.s:
        if self.charDict[key] == 1:
            return key
    return '#'

def Insert(self, char):
    self.charDict[char] = 1 if char not in self.charDict else self.charDict[char]+1
    self.s += char

猜你喜欢

转载自blog.csdn.net/u010005281/article/details/80232522