当前位置:   article > 正文

LeetCode387:字符串中的第一个唯一字符_编程题:字符串中的第一个唯一字符

编程题:字符串中的第一个唯一字符

目录

一、题目

二、示例

三、思路

四、代码


一、题目

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

二、示例

示例:

    s = "leetcode"

    返回 0

    s = "loveleetcode"

    返回 2

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

三、思路

方法一:

利用 OrderedDict 创建有序字典。OrderedDict 是 dict 子类,它记住了内容添加的顺序

因此,第一步,创建有序字典;第二步,遍历,直到value值为1,并返回该key的索引值。

方法二:

利用 Counter 计数器计算出每个字符出现的个数。Counter dict 子类,提供计数器工具以支持方便快捷的计数

因此,第一步Counter 计数器计算出每个字符出现的个数;第二步,遍历字符串 s,返回出现次数为1的字符的索引。

四、代码

1、

  1. import collections
  2. class Solution:
  3. def firstUniqChar(self, s: str) -> int:
  4. """
  5. :param s: str
  6. :return: int
  7. """
  8. dict_s = collections.OrderedDict()
  9. for i in s:
  10. if i not in dict_s:
  11. dict_s[i] = 1
  12. else:
  13. dict_s[i] += 1
  14. # print(dict_s)
  15. for i in dict_s:
  16. if dict_s[i] == 1:
  17. return s.index(i)
  18. return -1
  19. if __name__ == '__main__':
  20. # s = "leetcode"
  21. # s = "dddccdbba"
  22. s = "loveleetcode"
  23. S = Solution()
  24. ans = S.firstUniqChar(s)
  25. print(ans)

2、

  1. import collections
  2. class Solution:
  3. def firstUniqChar(self, s: str) -> int:
  4. S = collections.Counter(s)
  5. for i, ch in enumerate(s):
  6. if S[ch] == 1:
  7. return i
  8. return -1
  9. if __name__ == '__main__':
  10. # s = "leetcode"
  11. # s = "dddccdbba"
  12. s = "loveleetcode"
  13. S = Solution()
  14. ans = S.firstUniqChar(s)
  15. print(ans)

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/727439
推荐阅读
相关标签
  

闽ICP备14008679号