题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)。
解题思路
可以使用哈希表把每个字符出现的次数都存下来,然后遍历字符串,判断哈希表中value是否为1。Python用dict来实现哈希表。
代码
Python(2.7.3)
1
2
3
4
5
6
7
8
9
10
11# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
hashset = {}
for i in s:
hashset[i] = hashset.setdefault(i, 0) + 1
for i in range(len(s)):
if hashset[s[i]] == 1:
return i
return -1运行时间:27ms
占用内存:5624k