387. First Unique Character in a String – 哈希表、字典
注:
涉及到统计个数之类的题目,大部分都可以使用字典(hashmap)来解。
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.
解1:
标准的字符个数统计代码。
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
#使用字典来解,哈希表
#return min([s.find(c) for c,v in collections.Counter(s).iteritems() if v==1] or [-1])
d = {}
for i in s:
if i in d.keys():
d[i] += 1
else:
d[i] = 1
for j in range(len(s)):
if d[s[j]] == 1:
return j
return -1
解2:
使用了collections.Counter()函数,统计字符出现的个数,并放回一个字典。
iteritems()放回 键-值对。
return min([s.find(c) for c,v in collections.Counter(s).iteritems() if v==1] or [-1])