原题
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.
解法
使用字典计数, 然后遍历s, 返回第一个计数为1的index.
Time: O(n)
Space: O(1)
代码
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d = collections.Counter(s)
for i, ch in enumerate(s):
if d[ch] == 1:
return i
return -1