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

329 阅读1分钟

要求

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

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

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

核心代码

class Solution:
    def firstUniqChar(self, s: str) -> int:
        import collections
        dic = collections.Counter(s)
        for i,char in enumerate(s):
            if dic[char] == 1:
                return i
        return -1

另一解法

class Solution:
    def firstUniqChar(self, s: str) -> int:
        l = len(s)
        for item in "abcdefghijklmnopqrstuvwxyz":
            a = s.find(item)
            b = s.rfind(item)
            if a == b and a !=-1:
                l = min(l,a)
        return l if l < len(s) else -1

image.png

解题思路:第一种解法:我们使用collections的Counter的方法,统计每个字符的个数,然后遍历字符串,输出个数一个的字符,不存在返回-1;第二种解法:如果输出限定在小写字母的范围内:则可以找每个字母出现的最左下标和最右下标,如果最左下标 == 最右下标,则说明出现次数为1,思路比较清奇,值得学习。