我读到一个面试问题,想为以下内容写些代码:Write an efficient function to find the first nonrepeated character in
a string. For instance, the first nonrepeated character in “total” is
'o' and the first nonrepeated character in “teeter” is 'r'. Discuss
the efficiency of your algorithm.
我在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
有没有更简洁有效的答案?