Skip to content

387 first unique character in a string

387. First Unique Character in a String

题目: https://leetcode.com/problems/first-unique-character-in-a-string/

难度: Easy

思路一:

Python作弊法

用Python的Counter模块

可以参考

https://pymotw.com/2/collections/counter.html

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = collections.Counter(s)
        for x,c in enumerate(s):
            if d[c] == 1:
                return x
        return -1

思路二:

利用问题的特性,因为只有可能是小写字母,所以可以用一个长度为26的array, 先数一遍char的数量,然后enumerate从左往右又来

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        cnt = [0 for i in range(26)]
        for char in s:
            cnt[ord(char) - ord('a')] += 1

        for idx, char in enumerate(s):
            if cnt[ord(char) - ord('a')] == 1:
                return idx
        return -1 


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组