版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86556521
原题
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.
解法
先用字典存储每个字符出现的次数, 然后遍历字符串, 当出现字母次数为1时, 返回当前index.
Time: 2*O(n)
Space: O(1)
代码
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
count = collections.Counter(s)
for i, char in enumerate(s):
if count[char] == 1:
return i
return -1