34. 第一个只出现一次的字符
题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路
建立一个哈希表,第一次扫描的时候,统计每个字符的出现次数。第二次扫描的时候,如果该字符出现的次数为1,则返回这个字符的位置。时间复杂度为
代码实现
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
length = len(s)
if length == 0:
return -1
str_hash = {}
for i in range(length):
if s[i] in str_hash:
str_hash[s[i]] += 1
else:
str_hash[s[i]] = 1
for i in range(length):
if str_hash[s[i]] == 1:
return i
return -1
京公网安备 11010502036488号