我读到一个工作面试问题,为以下内容编写一些代码:
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
有没有更简洁高效的答案?
最佳答案
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'
编辑:如果您想在不使用像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
关于python - 查找字符串中的第一个非重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14511340/