美文网首页
LeetCode-387 字符串中的第一个唯一字符

LeetCode-387 字符串中的第一个唯一字符

作者: FlyCharles | 来源:发表于2019-02-23 20:45 被阅读0次

1. 题目

https://leetcode-cn.com/problems/first-unique-character-in-a-string/

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

注意事项:您可以假定该字符串只包含小写字母。


2. 我的AC

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        mapping = {}
        for char in s:
            if char not in mapping:
                mapping[char] = 1
            else:
                mapping[char] += 1
        for i in range(len(s)):
            if mapping[s[i]] == 1:
                return i
        else:
            return -1

3. 小结

  1. 字典的值列表
  • dict.values() 以列表返回字典中的所有值
  1. 列表索引
  • list.index(obj) 某个值第一个匹配项的索引位置
  1. 遍历字典元素
  • for key in d: 得到元素的键
  • key, value in d.iteritems(): 访问键和对应的值

相关文章

网友评论

      本文标题:LeetCode-387 字符串中的第一个唯一字符

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