Find the first non-repeated character in a string

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

    input_str = "interesting"
    #input_str = "aabbcc"
    #input_str = "aaaapaabbcccq"
    
    
    def firstNonRepeating(param):
        counts = {}        
        for i in range(0, len(param)):
    
        # Store count and index repectively
            if param[i] in counts:
                counts[param[i]][0] += 1
            else:
                counts[param[i]] = [1, i]
    
        result_index = len(param) - 1
        for x in counts:
            if counts[x][0] == 1 and result_index > counts[x][1]:
                result_index = counts[x][1]
        return result_index
    
    result_index = firstNonRepeating(input_str)
    if result_index == len(input_str)-1:
        print("no such character found")
    else:
        print("first non repeating charater found: " + input_str[result_index])
    

提交回复
热议问题