1.创建一个history记录出现过的字符,使用另一个list储存是否只出现一次。如果再次出现则从list中删除,最后返回list[0]
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
s_history = []
first_s = []
first_index = []
for i in range(len(s)):
if s[i] not in s_history:
first_s.append(s[i])
first_index.append(i)
s_history.append(s[i])
elif s[i] in first_s:
index = first_s.index(s[i])
first_s.pop(index)
first_index.pop(index)
return first_index[0] if first_index else -12.使用harsh表,利用字符的ASCLL码作为key。value记录其出现的次数。
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
s_ascll = {}
for i in range(len(s)):
if ord(s[i]) in s_ascll:
s_ascll[ord(s[i])][0] += 1
else:
s_ascll[ord(s[i])] = [1, i]
for i in range(len(s)):
if s_ascll[ord(s[i])][0] == 1:
return s_ascll[ord(s[i])][1]
return -1
京公网安备 11010502036488号