题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
假定该字符串只包含小写字母。
示例
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.
解答
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
# 统计字符及其第一次出现的索引及出现次数
s_dict = dict()
for i in range(0,length):
char = s[i]
if char not in s_dict.keys():
s_dict[char] = [i,0]
s_dict[char][1] = s_dict[char][1] + 1
ind_list = list() # 无重复字符的索引
flag = False # 记录是否有无重复字符存在
for ind_count in s_dict.values():
if ind_count[1] == 1:
ind_list.append(ind_count[0])
flag = True
if flag:
return min(ind_list)
return -1