Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
cur = 0
for i in s: # 用一个字典记录所有只出现一次的字母的index,多次出现的字母index置-1
if i not in d:
d[i] = cur
else:
d[i] = -1
cur += 1
_min = len(s)
for k, v in d.items(): # 找到只出现一次的字母的最小的index
if v != -1 and v < _min:
_min = v
return _min if _min != len(s) else -1 # 如果没找到(_min没变化),则返回-1