思路:
利用哈希表,哈希表的下标是字符的ASCII值,值为字符出现的次数。
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
#建立哈希表,字符长度为8的数据类型,共有256种可能,于是创建一个长度为256的列表
ls=[0]*256
#遍历字符串,下标为字符的ASCII值,值为该字符出现的次数
for i in s:
ls[ord(i)]+=1
#遍历列表,找到出现次数为1的字符并输出位置
for j in s:
if ls[ord(j)]==1:
return s.index(j)
return -1
另一种做法:
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if len(s)<0:
return -1
for i in s:
if s.count(i)==1:
return s.index(i)
return -1
count()函数可以统计每个字符出现的个数。