每日一题力扣387

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

错解:

理解错题意了

class Solution:
    def firstUniqChar(self, s: str) -> int:
        for i in range(len(s)):
            for j in range(i+1,len(s)):
                if s[i]!=s[j]:
                    return i

正解:

class Solution:
    def firstUniqChar(self, s: str) -> int:
        d=dict()
        for i in s:
            d[i]=d.get(i,0) +1
        for idx,x in enumerate(s):
            if d[x]==1:
                return idx
        return -1
原文地址:https://www.cnblogs.com/liuxiangyan/p/14529488.html