其他分享
首页 > 其他分享> > 每日一题力扣387

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

 

标签:return,int,self,Solution,len,力扣,387,firstUniqChar,一题
来源: https://www.cnblogs.com/liuxiangyan/p/14529488.html