在字符串中查找第一个不重复的字符

Jur*_*ocs 2 python algorithm

我读了一份求职面试问题,为下面写了一些代码:

编写一个有效的函数来查找字符串中的第一个非重复字符.例如,"total"中的第一个非重复字符是"o","teeter"中的第一个非重复字符是"r".讨论算法的效率.

我在Python中提出了这个解决方案; 但是,我确信有更好的方法可以做到这一点.

word="googlethis"
dici={}

#build up dici with counts of characters
for a in word:
    try:
        if dici[a]:
            dici[a]+=1
    except:
        dici[a]=1

# build up dict singles for characters that just count 1 

singles={}
for i in dici:
    if dici[i]==1:
        singles[i]=word.index(i)

#get the minimum value

mini=min(singles.values())

#find out the character again iterating...

for zu,ui in singles.items():
    if ui==mini:
        print zu 
Run Code Online (Sandbox Code Playgroud)

有更简洁有效的答案吗?

ins*_*get 8

In [1033]: def firstNonRep(word):
   ......:     c = collections.Counter(word)
   ......:     for char in word:
   ......:         if c[char] == 1:
   ......:             return char
   ......:         

In [1034]: word="googlethis"

In [1035]: firstNonRep(word)
Out[1035]: 'l'
Run Code Online (Sandbox Code Playgroud)

编辑:如果你想在不使用帮助器的情况下实现相同的功能Counter:

def firstNonRep(word):
    count = {}
    for c in word:
        if c not in count:
            count[c] = 0
        count[c] += 1
    for c in word:
        if count[c] == 1:
            return c
Run Code Online (Sandbox Code Playgroud)

  • @ dm03514:`Counter`不是保留订单.但是如果你注意到,我会遍历单词中的字符.因此返回单词中的第一个非重复字符 (8认同)
  • 是`Counter`订购可靠吗?我认为不是吗? (2认同)