给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
方案一:假定只包含小写字母。
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
lowercase = 'abcdefghijklmnopqrstuvwxyz'
res = [s.index(label) for label in lowercase if s.count(label) == 1]
if len(res):
return min(res)
return -1
方案二:用字典记录各字符的索引。如果重复出现,则索引值需要加上len(s)
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
for i in range(len(s)):
if s[i] not in d:
d[s[i]] = i
else:
d[s[i]] += len(s)
if len(s) and min(d.values()) < len(s) :
return min(d.values())
return -1