【Leetcode每日笔记】387. 字符串中的第一个唯一字符(Python)

题目

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

示例:

s = “leetcode” 返回 0

s = “loveleetcode” 返回 2

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

解题思路

哈希表

对字符串每个元素出现的次数进行计数,找出第一个不重复的字符,再遍历一次字符串,找到字符所在位置的索引即可。

代码

class Solution:
    def firstUniqChar(self, s: str) -> int:
        s_dic = collections.Counter(s)
        for key in s_dic:
            if s_dic[key] == 1:
                return s.index(key)
        return -1

猜你喜欢

转载自blog.csdn.net/qq_36477513/article/details/111571487
今日推荐