Find the first non-repeated character in a string

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

    def non_repeating(given_string):
        try:
            item = [x for x in given_string[:] if given_string[:].count(x) == 1][0]
        except:
            return None
        else:
            return item
    
    # NOTE: The following input values will be used for testing your solution.
    print non_repeating("abcab") # should return 'c'
    print non_repeating("abab") # should return None
    print non_repeating("aabbbc") # should return 'c'
    print non_repeating("aabbdbc") # should return 'd'
    

提交回复
热议问题