Find the first non-repeated character in a string

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

    Question: 1st non-repeating character in a string

    Method 1: making a count array

    a = "GGGiniiiiGinaaaPrrrottiijayi"
    count = [0]*256
    for ch in a: count[ord(ch)] +=1
    for ch in a :
        if( count[ord(ch)] == 1 ):
            print(ch)
            break
    

    Method2: List comprehension

    # 1st  non repeating character
    pal = [x for x in a if a.count(x) == 1][0]
    print(pal)
    

    Method 3: dictionary

    d={}
    for ch in a: d[ch] = d.get(ch,0)+1
    aa = sorted(d.items(), key = lambda ch  :ch[1])[0][0]
    print(aa)
    

提交回复
热议问题