剑指34-第一个只出现一次的字符位置

题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).


字典记录,前后只要遍历两次,复杂度是O(n)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if len(s) == 0:
return -1
mydict = {}
for char in s:
if not mydict.has_key(char):
mydict[char] = 1
else:
mydict[char] += 1
for i in range(len(s)):
if mydict[s[i]] == 1:
return i
return -1