leetcode_387. First Unique Character in a String 找第一个非重复的字符下标,python字典的应用

题目:

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

题意:

给定一个字符串,写一个函数找到这个字符串中第一个非重复字符出现的下标。


代码:

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
    
        dict_num = dict()
        
        for x in s :
            dict_num[x] = 0
        
        for x in s :
            dict_num[x] = dict_num[x] + 1               #存储各字符出现的次数
        
        for i in range(len(s)) :              #在s中遍历,判断当前字符出现次数是否为1
            if dict_num[s[i]] == 1 :
                return i
        return -1


笔记:

用字典dict_num存储字符串s中各字符出现的次数,其中dict_num中各key值是按照字母在字典中的顺序存储的。

即假设s='leetcode',其对应的dict_num的内容如下:

{u'c': 1, u'e': 3, u'd': 1, u'l': 1, u'o': 1, u't': 1}

可见最后在判断s中第一个不重复的字符时,不能在dict_num中遍历,因为dict_num中第一个value值为1的字符在s中可能并不是第一个。  故应该在s中遍历,判断当前字符在dict_num中value是否为1.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值