每日一题力扣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

 

posted @ 2021-03-13 16:56  小千北同学超爱写代码  阅读(41)  评论(0编辑  收藏  举报