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

2019-02-23  本文已影响0人  FlyCharles

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. 字典的值列表
  1. 列表索引
  1. 遍历字典元素
上一篇 下一篇

猜你喜欢

热点阅读