The first character that is not repeated in the character stream.

Title Description

Please implement a function to find out the first character in the character stream. For example, when the first two characters “go” are read out from a character stream, the first character that appears only once is “g”. When the first six characters “Google” are read from the character stream, the first word appears only once.The symbol is “L”. If the current character stream does not exist once, it returns the character.

thinking

It’s similar to the character that only appears once in the preceding string, but not the same. The preceding string is a fixed-length string, and the problem is a character stream, that is, it will grow. Each time a character is added to the string, it is necessary to re-determine which character appears only once.

Because the python for offer is only 2.7, no more than 3.0, and the dictionary traversal of Python 2.7 is usually not ordered (python 3 is usually ordered), you can only use a list to store all the strings, traverse the strings, and so on.Seek

Answer

class Solution:
    # Return to corresponding char
    def __init__(self):
        self.charDict = {}#Storing characters and corresponding quantitiesSelf.charlist= []#Store characterdef FirstAppearingOnce(self):
        # write code here
        for key in self.charlist:
            if self.charDict[key]==1:
                return key
        return '#'
    def Insert(self, char):
        # write code here
        self.charDict[char]=1 if char not in self.charDict else self.charDict[char]+1
        self.charlist.append(char)

Well, if you think about it again, it’s perfectly OK to remove the dictionary. It’s not fundamentally different from the fixed length string that appears only once.

class Solution:
    # Return to corresponding char
    def __init__(self):
        self.charlist = []
    def FirstAppearingOnce(self):
        # write code here
        for key in self.charlist:
            if self.charlist.count(key)==1:
                return key
        return '#'
    def Insert(self, char):
        # write code here
        self.charlist.append(char)

 

Leave a Reply

Your email address will not be published. Required fields are marked *