查找字符串中的第一个非重复的字符 [英] Find the first non-repeated character in a string

查看:132
本文介绍了查找字符串中的第一个非重复的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读的面试问题,写一些code以下:

  

编写一个有效的功能,找到第一个nonrepeated字符   一个字符串。例如,在总的第一个字符nonrepeated是   O和步履蹒跚的第一个nonrepeated字符是'R'。讨论   你的算法的效率。

我想出了这个解决方案在Python;但是,我敢肯定有做更漂亮的方式方法。

 字=googlethis
DICI = {}

#build了DICI与字符计数
对于以字:
    尝试:
        如果DICI并[a]:
            DICI [α] = + 1
    除:
        DICI [α] = 1

#建立词典单打角色,仅仅数1

单打= {}
因为我在DICI:
    如果DICI [我] == 1:
        单打[我] = word.index(I)

#获取的最小值

迷你=分钟(singles.values​​())

再次#find出的字符迭代...

为祖,UI在singles.items():
    如果UI ==小:
        打印祖
 

有没有更简洁高效的答案吗?

解决方案

 在[1033]:高清firstNonRep(字):
   ......:C = collections.Counter(字)
   ......:对于焦炭的字:
   ......:如果C [字符] == 1:
   ......:返回字符
   ......:

在[1034]字=googlethis

在[1035]:firstNonRep(字)
出[1035]:'L'
 

修改:如果要实现同样的事情,而无需使用助手像计数器

 高清firstNonRep(字):
    数= {}
    对于C中的一句话:
        如果c不计:
            算上[C] = 0
        算上[C] + = 1
    对于C中的一句话:
        如果计数[C] == 1:
            回复C
 

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 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.

I came up with this solution in Python; but, I'm sure that there are way more beautiful ways of doing it.

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 

Is there a more concise and efficient answer?

解决方案

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'

EDIT: If you want to implement the same thing without using helpers like 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

这篇关于查找字符串中的第一个非重复的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆