Find the first un-repeated character in a string

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

    Here is another fun way to do it. Counter requires Python2.7 or Python3.1

    >>> from collections import Counter
    >>> def first_non_repeated_character(s):
    ...     return min((k for k,v in Counter(s).items() if v<2), key=s.index)
    ...
    >>> first_non_repeated_character("aaabbbcffffd")
    'c'
    >>> first_non_repeated_character("aaaebbbcffffd")
    'e'
    

提交回复
热议问题