Re: [閒聊] 每日LeetCode

作者: pandix (麵包屌)   2024-02-05 18:11:58
※ 引述《yam276 (史萊哲林的優等生)》之銘言:
: 標題: Re: [閒聊] 每日LeetCode
: 時間: Mon Feb 5 17:51:20 2024
:
: ※ 引述《JerryChungYC (JerryChung)》之銘言:
: : https://leetcode.com/problems/first-unique-character-in-a-string
: : 387. First Unique Character in a String
: : 給一個字串s,找到第一個不重複的字元回傳其索引,不存在則回傳-1
: : Example 1:
: : Input: s = "leetcode"
: : Output: 0
: : Example 2:
: : Input: s = "loveleetcode"
: : Outpue: 2
: : Example 3:
: : Input: s = "aabb"
: : Output: -1
: → wu10200512: 有一個迴圈解決的方法嗎 02/05 17:52
可以用 python dict 保留插入順序的性質
如果是第一次出現的字元就把他的 index 記在 dict 裡
如果不是就把他的 index (如果有的話) 刪掉
這樣最後在 dict.items()[0] 的就會是最早出現的那個字元
class Solution:
def firstUniqChar(self, s: str) -> int:
char, idx = set(), {}
for i, c in enumerate(s):
if c in char:
if c in idx:
del idx[c]
else:
char.add(c)
idx[c] = i
#return (list(idx.values())+[-1])[0]
return next(iter(idx.values())) if idx else -1
不過這種 python dict 又和一般的 hash table 不一樣了
所以可能不是你要的
(改了一下拿 dict[0] 的方法)
作者: rp20031219 (Tim87)   2024-02-05 18:22:00
哇 阿屌
作者: wu10200512 (廷廷)   2024-02-05 18:40:00
你好強

Links booklink

Contact Us: admin [ a t ] ucptt.com