Find the first non-repeated character in a string

前端 未结 21 1582
有刺的猬
有刺的猬 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:28

    Simple Python3 solution

    def findFirstUniqueChar(s):
        d = {}
        for c in s:
            if c in d:
                d[c] += 1
            else:
                d[c] = 1
    
        for c in s:
            if d[c] == 1:
                return s.index(c)
        return -1
    

提交回复
热议问题