题目
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
暴力解法
- 遍历字符串
- 计算每一个元素出现的次数
- 当某一元素出现次数为1时,返回该元素的索引值
- 若没有找到这个元素,就返回-1
class Solution:
def firstUniqChar(self, s: str) -> int:
for i in s:
if s.count(i)==1:
return s.index(i)
return -1
使用collections函数
collections的counter函数能够计算字符串中每个元素出现的次数,并以字典的形式保存。
- 使用counter函数统计每个元素出现的次数并保存在n中。
- 遍历s中的元素
- 在n中查询当前元素的出现次数,如果等于1就返回当前元素的索引值
- 若没有找到唯一出现的字符,就返回-1
class Solution:
def firstUniqChar(self, s: str) -> int:
n=collections.Counter(s)
for i in s:
if n[i]==1:
return s.index(i)
return -1