Re: [閒聊] 每日LeetCode已回收
※ 引述《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] 的方法)
--
沒人在乎
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.165.42.122 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1707127923.A.37E.html
→
02/05 18:22,
1年前
, 1F
02/05 18:22, 1F
※ 編輯: pandix (118.165.42.122 臺灣), 02/05/2024 18:31:01
推
02/05 18:40,
1年前
, 2F
02/05 18:40, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 653 之 719 篇):