题目描述:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.
注意事项:您可以假定该字符串只包含小写字母。
#代码1(时间太长未通过):
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
for i in range(0,len(s)):
if(s.count(s[i])==1):
return i
break
return -1
#代码2:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
list1=[]
letter="abcdefghijklmnopqrstuvwxyz"
order=[]
for i in letter:
if (s.count(i)==1):
list1.append(s.index(i))
if(list1):
return min(list1)
else:
return -1
总结:使用方法一逐个遍历字符串中的每一个字符,但当字符串太长时会因为时间运行时间太长无法AC。
可尝试逐个遍历26个英文字母,将所有个数唯一的字母在字符串中的下标存入list中,list中的最小值即第一次穿出现的唯一字符的下标。