LeetCode-387. 字串中的第一個唯一字元(python3.7)
阿新 • • 發佈:2020-12-27
給定一個字串,找到它的第一個不重複的字元,並返回它的索引。如果不存在,則返回 -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模組的帖子