剑指Offer 字符流中第一个只出现一次的字符

题目:

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是’g’。当从该字符流中读出前六个字符”google”时,第一个只出现一次的字符是’l’。如果当前字符流没有存在出现一次的字符,返回#字符。
样例
输入:“google”
输出:“ggg#ll”
解释:每当字符流读入一个字符,就进行一次判断并输出当前的第一个只出现一次的字符。

解答:

class Solution: 
    def __init__(self):
        self.d = {}
        self.ind = 0
    def firstAppearingOnce(self):
        """
        :rtype: str
        """
        minInd = self.ind
        ch = None
        for i in self.d:
            if len(self.d[i]) == 1 and self.d[i][0] < minInd:
                minInd = self.d[i][0]
                ch = i
        return ch if ch else '#'
                
    def insert(self, char):
        """
        :type char: str
        :rtype: void
        """
        if char not in self.d:
            self.d[char] = [self.ind]
        else:
            self.d[char].append(self.ind)
        self.ind += 1      

猜你喜欢

转载自blog.csdn.net/u013796880/article/details/84845420