387. First Unique Character in a String python3

387. First Unique Character in a String python3_第1张图片
题目截图

题目翻译:

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

Note:

假设字符串只包含小写字母。

题目思路:

  1. 使用collections模块的Counter()类,在字典中保存每个字符出现的次数。
  2. 遍历字符串,参考字典中对应的次数,若对应的次数为1,则返回该字符。

代码如下:

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        import collections
        key_dict = {}
        key_dict = collections.Counter(s) #将s中每个字符及其出现的次数保存在字典中
        for i in range(0, len(s)):
            if key_dict[s[i]] == 1:
                return i
        return -1

程序的时间复杂度为O(n)。

思路参考:

https://leetcode.com/articles/first-unique-character-in-a-string/

你可能感兴趣的:(387. First Unique Character in a String python3)