题目:
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.