跳转至

387. 字符串中的第一个唯一字符#

问题描述#

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

 

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

 

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

解题思路#

用下标的正负性表示某字符是否重复出现。


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def firstUniqChar(self, s: str) -> int:
        arr = [0] * 26
        for i, c in enumerate(s, 1):
            k = ord(c) - 97
            if arr[k] == 0:
                arr[k] = i
            elif arr[k] > 0:
                arr[k] = -arr[k]

        d = list(filter(lambda x: x > 0, arr))
        return min(d) - 1 if d else -1
返回顶部

在手机上阅读