387. 字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.
注意事项:您可以假定该字符串只包含小写字母。
解题思路一:使用字典d记录s中各个字符出现的次数,然后从前向后遍历s,返回第一个次数等于1的字符的位置。
Python3代码如下:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
for i in s:
if i in d:
d[i] += 1
else:
d[i] = 1
for i in range(len(s)):
if d[s[i]] == 1:
return i
return -1
解题思路二:遍历26个小写字母,找到各个小写字母中唯一出现的字母并记录其位置,求这些位置的最小值即可。
Python3代码如下:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
a,b = 'qwertyuiopasdfghjklzxcvbnm',float('inf')
for c in a:
i = s.find(c)
if i == -1:
continue
j = s.find(c,i+1)
if j == -1:
b = min(i,b)
return b if b != float('inf') else -1