文章目录
字符串中的第一个唯一字符
题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
code
class Solution:
def firstUniqChar(self, s: str) -> int:
"""
:type s: str
:rtype: int
"""
# build hash map : character and how often it appears
count = collections.Counter(s) # Counter是一个类
# find the index
# enumerat() 函数讲一个可遍历的数据对象 组合成一个索引序列,同时列出
# 同时列出数据和数据下表,一般用在for循环中
for idx, ch in enumerate(s):
if count[ch] == 1:
return idx
return -1