Find the first un-repeated character in a string

后端 未结 30 1293
猫巷女王i
猫巷女王i 2020-11-27 18:29

What is the quickest way to find the first character which only appears once in a string?

30条回答
  •  一整个雨季
    2020-11-27 19:12

    I read through the answers, but did not see any like mine, I think this answer is very simple and fast, am I wrong?

    def first_unique(s):
        repeated = []
    
        while s:
            if s[0] not in s[1:] and s[0] not in repeated:
                return s[0]
            else:
                repeated.append(s[0])
                s = s[1:]
        return None
    

    test

    (first_unique('abdcab') == 'd', first_unique('aabbccdad') == None, first_unique('') == None, first_unique('a') == 'a')
    

提交回复
热议问题