美文网首页
华为机考题 | 字符串中的第一个唯一字符----python实现

华为机考题 | 字符串中的第一个唯一字符----python实现

作者: 金融测试民工 | 来源:发表于2020-02-16 11:30 被阅读0次

    题目描述

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

    案例1:

    s = "leetcode"

    返回 0.

    案例2:

    s = "loveleetcode",

    返回 2.

    解答:这道题也完全迎合了Python中的Counter类,只有返回字典里第一个key为1的值就好。

    from collections import Counter

    class Solution:

        def firstUniqChar(self,s: str)-> int:

            c = Counter(s)

            for key in c:

                if c[key]== 1:

    return s.find(key)

            return -1

    相关文章

      网友评论

          本文标题:华为机考题 | 字符串中的第一个唯一字符----python实现

          本文链接:https://www.haomeiwen.com/subject/nkrpfhtx.html