Find the first non-repeated character in a string

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

    I think the worst case is O(n^2) but looks clear for me:

    def firstNonRep(word):
        """the first non-repeating character in a string: "ABCA" -> B """
        for (i, c) in enumerate(word):
            residual = word[i+1:]
            if not c in residual:
                return c
    

提交回复
热议问题