offer-35在一个字符串中找到第一个只出现一次的字符

来源:互联网 发布:python 交易策略 模拟 编辑:程序博客网 时间:2024/06/14 16:37
# coding=utf-8'''在一个字符串中找到第一个只出现一次的字符,建立hash表'''def firstfind(s):    if s==None or len(s)<=0:        return  -1    alphabet={} #建立一个空字典,字母是key,出现的次数是value    alist=list(s)#将字符串转成list,放到列表中遍历    for i in alist:        if i  not in alphabet.keys():#当字母不在字典中时,次数初始化为0,如果在直接加1            alphabet[i]=0        alphabet[i]+=1    for i in alist:#构建hash表后再遍历一次即可        if alphabet[i]==1:            return i    return -1if __name__ == '__main__':    print(firstfind('ababcdcf'))
阅读全文
0 0
原创粉丝点击