建立有序哈希表。遍历字符串,用字符作为key,用一个list作为value,list的两个值分别记录字符出现的次数和第一次出现的位置。
python
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
import collections
dic = collections.OrderedDict() #记录字母出现的次数和位置
for i,c in enumerate(s):
if c not in dic:
dic[c]=[1,i]
else:
dic[c][0]+=1
for k,v in dic.items():
if v[0]==1:
return v[1]
return -1