第一个只出现一次的字符

###题目

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

解题思路

Python 3中的字典有序;Python 2只能使用collections.OrderedDict()。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding:utf-8 -*-
import collections
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
l = list(s)
if len(l) == 0:
return -1
d = collections.OrderedDict()
for i in range(0, len(l)):
d[l[i]] = 0
for i in range(0, len(l)):
d[l[i]] = d[l[i]] + 1
for key in d:
if d[key] == 1:
return l.index(key)
return -1