在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
使用python内置函数:
class Solution:
def FirstNotRepeatingChar(self, s):
if not s:
return -1
try:
s = s.strip()
for i,c in enumerate(s):
if s.count(c)==1:
return i
break
except:
return -1
使用collections.OrderedDict
【1】OrderedDict是有顺序的,而Dict是无序的。
from collections import OrderedDict
class Solution:
def FirstNotRepeatingChar(self, s):
hashTable = OrderedDict()
for i in s:
if i not in hashTable:
hashTable[i] = 1
else:
hashTable[i] += 1
for j in hashTable:
if hashTable[j] == 1:
return s.index(j)
return -1
使用数组实现简单的hash表
【2】ord() 给定一个Unicode字符,返回ASCII码;A-Z的ASCII码为65-90,a-z的ASCII码值为97-122
class Solution:
def FirstNotRepeatingChar(self, s):
ls = [0]*123
for i in s:
ls[ord(i)] += 1
for j in s:
if ls[ord(j)] == 1:
return s.index(j)
return -1
如果某字符只出现一次,那么该字符的从前往后的索引和从后往前的索引是相等的
【3】index() 返回从前往后的第一个索引;rindex()返回从后往前的索引
还可使用find() 和 rfind(),不同之处在于 index() 查不到时抛出异常,而find() 返回-1
class Solution:
def FirstNotRepeatingChar(self, s):
for i in s:
if s.index(i) == s.rindex(i):
return s.index(i)
return -1