Find the first non-repeated character in a string

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

    Since we need the first non-repeating character, it is better to use OrderedDict from collections because dict does not guarantee the order of the keys

    from collections import OrderedDict
    dict_values = OrderedDict()
    string = "abcdcd"
    
    for char in string:
       if char in dict_values:
       dict_values[char] += 1
    else:
        dict_values[char] = 1
    
    for key,value in dict_values.items():
        if value == 1:
           print ("First non repeated character is %s"%key)
           break
        else:
           pass
    

提交回复
热议问题