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