字符串中的第一个唯一字符

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

注意事项:您可以假定该字符串只包含小写字母。

解答

In [2]:
class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        uniq = set()
        for idx, char in enumerate(s):
            if char in uniq:
                continue
            if char not in s[idx+1:]:
                return idx
            uniq.add(char)
        return -1

这里 in 的复杂度和 indexfind 的复杂度其实是一样的,都是 O(n) 级别。

利用了一个 set 来跳过某些判断,减少查找次数。

Comments !