Re: [閒聊] 每日LeetCode已回收
看板Marginalman作者JerryChungYC (JerryChung)時間1年前 (2024/02/06 07:23)推噓1(1推 0噓 0→)留言1則, 1人參與, 1年前最新討論串655/719 (看更多)
https://leetcode.com/problems/group-anagrams
※ 引述《oin1104 (是oin的說)》之銘言:
: 49. Group Anagrams
: 給你一些字串
: 把他們排序好
: 變成vector<vector<string>>
: 排序的規則是
: 當他們擁有的字母種類數量一樣就排在一起
: 像是dog god dgo 就排在一起
: dog god dgo pap ppa
: 就會變成前三個排在一起 後兩個排在一起
: 排在一起就好 順序沒差
Python3 code:
-----------------------------------------------------------------
from collections import defaultdict
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if len(strs) == 1: return [strs]
res = defaultict(list)
for s in strs:
res[''.join(sorted(s))].append(s)
return res.values()
-----------------------------------------------------------------
原本用Counter存到另一個List 再用index找出位置加進res 不過會TLE
後來想到存dict就好 不過Counter是unhashable
最後發現排序字元就好了
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.227.251.103 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1707204233.A.2E5.html
推
02/06 15:26,
1年前
, 1F
02/06 15:26, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 655 之 719 篇):