Find the first un-repeated character in a string

后端 未结 30 1401
猫巷女王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:05

    Refactoring a solution proposed earlier (not having to use extra list/memory). This goes over the string twice. So this takes O(n) too like the original solution.

    def first_non_repeated_character(s):
        counts = defaultdict(int)
        for c in s:
            counts[c] += 1
        for c in s:
            if counts[c] == 1:
                return c
        return None
    

提交回复
热议问题