🥉Easy

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例

  1. s = "leetcode"
  2. 返回 0
  3. s = "loveleetcode"
  4. 返回 2

提示:你可以假定该字符串只包含小写字母。

题解

思路挺简单的,就是遍历数组元素,遍历的同时用字典去存,然后遍历字典,遍历到第一个value为1的元素,就是要找的结果

Python

class Solution:
    def firstUniqChar(self, s: str) -> int:
        dicts={}
        for i in s:
            dicts[i]=dicts.get(i,0)+1
        for i in range(len(s)):
            if dicts[s[i]]==1:
                return i
        return -1

除了使用内置dict之外,还可以用collecton模块