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

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

s = "leetcode" 返回 0.s = "loveleetcode", 返回 2.

题解 我们使用所有小写的字母,这样即使最大字符串也只是循环26次 ,我们数每个字母在字符串中的个数等于一,我们就不它的下标存下来。
其中字符串的两个函数 index() , count()
ount() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置
index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
class Solution: def firstUniqChar(self, s: str) -> int: case = "abcdefghijklmnopqrstuvwxyz" res = [ s.index(label) for label in case if s.count(label) == 1 ] if len(res): return min(res) return -1

【LeetCode 字符串中的第一个唯一字符】

    推荐阅读