Find the first non-repeated character in a string

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

    The following code traverses through the string only once. It's a simple and easy solution for the problem but at the same time the space complexity is compromised.

    def firstNonRepeating(a):
        inarr = []
        outarr = []
    
        for i in a:
            #print i
            if not i in inarr:
                inarr.append(i)
                outarr.append(i)
            elif i in outarr:
                outarr.remove(i)
            else:
                continue
        return outarr[0]
    
    a = firstNonRepeating(“Your String”)
    print a
    

提交回复
热议问题