Find the first non-repeated character in a string

前端 未结 21 1524
有刺的猬
有刺的猬 2020-12-06 03:53

I read of a job interview question to write some code for the following:

Write an efficient function to find the first nonrepeated character in a st

21条回答
  •  南方客
    南方客 (楼主)
    2020-12-06 04:18

    In [1033]: def firstNonRep(word):
       ......:     c = collections.Counter(word)
       ......:     for char in word:
       ......:         if c[char] == 1:
       ......:             return char
       ......:         
    
    In [1034]: word="googlethis"
    
    In [1035]: firstNonRep(word)
    Out[1035]: 'l'
    

    EDIT: If you want to implement the same thing without using helpers like Counter:

    def firstNonRep(word):
        count = {}
        for c in word:
            if c not in count:
                count[c] = 0
            count[c] += 1
        for c in word:
            if count[c] == 1:
                return c
    

提交回复
热议问题