目录
一、题目
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
二、示例
示例:
s = "leetcode"
返回 0
s = "loveleetcode"
返回 2
扫描二维码关注公众号,回复: 12472039 查看本文章
- 提示:你可以假定该字符串只包含小写字母。
三、思路
方法一:
利用 OrderedDict 创建有序字典。OrderedDict 是 dict 的子类,它记住了内容添加的顺序。
因此,第一步,创建有序字典;第二步,遍历,直到value值为1,并返回该key的索引值。
方法二:
利用 Counter 计数器计算出每个字符出现的个数。Counter 是 dict 子类,提供计数器工具以支持方便快捷的计数。
因此,第一步,Counter 计数器计算出每个字符出现的个数;第二步,遍历字符串 s,返回出现次数为1的字符的索引。
四、代码
1、
import collections
class Solution:
def firstUniqChar(self, s: str) -> int:
"""
:param s: str
:return: int
"""
dict_s = collections.OrderedDict()
for i in s:
if i not in dict_s:
dict_s[i] = 1
else:
dict_s[i] += 1
# print(dict_s)
for i in dict_s:
if dict_s[i] == 1:
return s.index(i)
return -1
if __name__ == '__main__':
# s = "leetcode"
# s = "dddccdbba"
s = "loveleetcode"
S = Solution()
ans = S.firstUniqChar(s)
print(ans)
2、
import collections
class Solution:
def firstUniqChar(self, s: str) -> int:
S = collections.Counter(s)
for i, ch in enumerate(s):
if S[ch] == 1:
return i
return -1
if __name__ == '__main__':
# s = "leetcode"
# s = "dddccdbba"
s = "loveleetcode"
S = Solution()
ans = S.firstUniqChar(s)
print(ans)