Python解法:哈希
class Solution: def FirstNotRepeatingChar(self, s): # write code here l=[0]*256 for i in s:#记录每个字符出现的次数 l[ord(i)]+=1 for j,v in enumerate(s):#再按照s的顺序去查看l中次数为1的字符 if l[ord(v)]==1: return j return -1
另外也可以借助计数字典实现,代码如下:
from collections import Counter class Solution: def FirstNotRepeatingChar(self, s): # write code here dict=Counter(s) for j,v in enumerate(s): if dict[v]==1: return j return -1