Find the first non-repeated character in a string

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

    My solution. I can't speak to how efficient it is; I think it runs in n^2 time.

    >>> def fst_nr(s):
    ...     collection = []
    ...     for i in range(len(s)):
    ...             if not s[i] in collection and not s[i] in s[i+1:]:
    ...                     return s[i]
    ...             else:
    ...                     collection+=[s[i]]
    ... 
    >>> fst_nr("teeter")
    'r'
    >>> fst_nr("floccinaucinihilipilification")
    'u'
    >>> fst_nr("floccinacinihilipilification")
    'h'
    >>> fst_nr("floccinaciniilipilification")
    'p'
    >>> fst_nr("floccinaciniiliilification")
    't'
    >>> fst_nr("floccinaciniiliilificaion")
    >>> 
    

    Any advice for a humble Stack noob?

提交回复
热议问题