题目描述:
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
解题思路:
第一遍扫描数组时得到hash表(每个字母的频率计数),第二遍扫描数组,每次从hash表中取出频率,第一个频率为1的即为所求。时间复杂度O(n)
解答:
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
countDict = {}
for ch in s:
countDict[ch] = countDict.get(ch, 0) + 1
for ind in range(len(s)):
ch = s[ind]
if countDict[ch] == 1:
return ind
return -1