1. 程式人生 > 其它 >LeetCode-387. 字串中的第一個唯一字元(python3.7)

LeetCode-387. 字串中的第一個唯一字元(python3.7)

技術標籤:practicepythonleetcode

給定一個字串,找到它的第一個不重複的字元,並返回它的索引。如果不存在,則返回 -1。

示例:

s = "leetcode"
返回 0
s = "loveleetcode"
返回 2

提示:你可以假定該字串只包含小寫字母。

from collections import defaultdict
class Solution:
    def firstUniqChar(self, s: str) -> int:
        d = defaultdict(int)
        for
key in s: d[key] += 1 for k,i in d.items(): if i == 1: return s.index(k) #因為預設有序 證明是第一個出現的 else: return -1

注:python3.6之後字典預設有序

此外 貼個解釋collection模組的帖子在這裡插入圖片描述

https://www.jianshu.com/p/8acb163dd1fe.