版权声明:此BLOG为个人BLOG,内容均来自原创及互连网转载。最终目的为记录自己需要的内容或自己的学习感悟,不涉及商业用途,转载请附上原博客。 https://blog.csdn.net/bulo1025/article/details/86369977
题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.
思路分析
- 关键问题在于,如何找到第一个不重复字符。可以新建一个字典,用key表示对应s中的字符,value表示出现的次数,如果第一次出现,则往后新建key,如果不是第一次出现,value += 1
- 顺序遍历s,从而在letters中保留了原来s中的顺序。
代码示例
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters = {}
for ch in s:
if ch not in letters:
letters[ch] = 1
else:
letters[ch] += 1
for i in range(len(s)):
if letters[s[i]] == 1:
return i
return -1