leetcode 387. 字符串中的第一个唯一字符 First Unique Character in a String【使用有序哈希表】

建立有序哈希表。遍历字符串,用字符作为key,用一个list作为value,list的两个值分别记录字符出现的次数和第一次出现的位置。

 

python

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        import collections
        dic = collections.OrderedDict()  #记录字母出现的次数和位置
        for i,c in enumerate(s):
            if c not in dic:
                dic[c]=[1,i]
            else:
                dic[c][0]+=1
        for k,v in dic.items():
            if v[0]==1:
                return v[1]
        return -1

 

全部评论

相关推荐

牛客52811839...:电商项目名字改一下,烂大街了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务