这个题在剑指offer里属于常规题,主要看编程语言的运用的如何巧。
python 常规操作,用count计数,index输出位置
class Solution():
def FirstNotRepeatingChar(self,s):
if len(s)<1:return -1
for i in s:
if s.count(i)==1:
return s.index(i)
break
return -1
大神压缩,一行Python代码搞定
class Solution():
def FirstNotRepeatingChar(self,s):
return [i for i in range(len(s)) if s.count(s[i])==1][0] if s else -1
采用内置函数
class Solution():
def FirstNotRepeatingChar(self,s):
return s.index(list(filter(lambda c:s.count(c)==1,s)[0]) if s else -1
使用哈希表
class Solution():
def FirstNotRepeatingChar(self,s):
Is=[0]*256
for i in s:
ls[ord[i]]+=1
for j in s:
if ls[ord[j]]==1:
return s.index(j)
break
return -1