[LeetCode] 49. Group Anagrams (Python)
Solution
import collections
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
answer = []
dic = collections.defaultdict(list)
# key: ์ ๋ ฌ๋ ๋ฌธ์์ด, value: ๊ธฐ์กด ๋ฌธ์์ด ๋ฆฌ์คํธ
# ์ฆ, ์ ๋ ฌ๋ ๋ฌธ์์ด์ธ key๊ฐ์ด ๊ฐ์ผ๋ฉด value์ ๊ณ์ append๊ฐ ๋๋ ํ์
for s in strs:
dic[''.join(sorted(s))].append(s)
return list(dic.values())
print(Solution().groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
Leave a comment