Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (caster )時間1年前 (2024/03/11 10:45), 編輯推噓3(301)
留言4則, 4人參與, 1年前最新討論串33/1554 (看更多)
※ 引述《Rushia (みけねこ的鼻屎)》之銘言: : https://leetcode.com/problems/custom-sort-string/description : 791. Custom Sort String : 給你一個字串s和一個表示字元排序優先的字串order,排序字串s,如果字元不在 order : 的話順序隨意。 : 思路: : 1.創建一個基於order索引的comparator丟給排序函數 : py code : ---------------------------------------------- : class Solution: : def customSortString(self, order: str, s: str) -> str: : dic = collections.defaultdict(lambda: ord(c) + 26) : for i, c in enumerate(order): : dic[c] = i : return ''.join(sorted(s, key=lambda x: dic[x])) : ---------------------------------------------- 思路: 用字典紀錄順序 之後sorted排序 為了避免key error 所以使用dic.get() 假如x不在dic 回傳27 Python Code: class Solution: def customSortString(self, order: str, s: str) -> str: dic = {} for i in range(len(order)): dic[order[i]] = i return "".join(sorted(s,key = lambda x : dic.get(x,27))) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.156.210 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1710125149.A.90E.html

03/11 10:46, 1年前 , 1F
大師
03/11 10:46, 1F

03/11 10:46, 1年前 , 2F
大師
03/11 10:46, 2F

03/11 10:47, 1年前 , 3F
大濕
03/11 10:47, 3F

03/11 11:08, 1年前 , 4F
大師
03/11 11:08, 4F
文章代碼(AID): #1bxd1TaE (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1bxd1TaE (Marginalman)