python - 查找字符串中的第一个非重复字符

标签 python algorithm

我读到一个工作面试问题,为以下内容编写一些代码:

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/

相关文章:

python - 如何在完整验证示例上评估 Tensorflow 模型

在 Windows 上实现并尝试在 Linux 上运行的代码的 Python 编译错误

forms - 在 Web 表单中保存项目列表的正确方法是什么?

javascript - 使用 JS 将页面中的每个字母设置为随机颜色。为什么在页面的每个开始标签之前总是有一组额外的 span 标签?

python - 来自多个列表的元素的最小组合,使得所有元素至少出现一次

c++ - 为什么 HSV-to-RGB 算法会这样工作?

algorithm - 查找算法是什么意思?

使用列表的 Python For 循环 - 尝试根据循环中使用的最后一个数字对数字对进行分组

python - 为什么 flake8 对于我在 "undefined name" block 中定义的内容说 `as`?

python - 如何获取每个嵌套列表的第三个元素,但如果第三个元素不存在则将其设置为 null?