题目:在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1.
牛客网:链接
建立一个哈希表,第一次扫描的时候,统计每个字符的出现次数。第二次扫描的时候,如果该字符出现的次数为1,则返回这个字符的位置。
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if not ss:
return -1
hash_dict = {}
for each in s:
if each not in hash_dict:
hash_dict[each] = 1
else:
hash_dict[each] += 1
for i in range(len(s)):
if hash_dict[s[i]] == 1:
return i
return -1