From 8bc155f949e50aaa54fd548e5d026b155e8dc3b4 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Tue, 7 Jan 2025 10:08:20 +0900 Subject: [PATCH] feat: [Week 05-2] solve group-anagrams --- group-anagrams/Chaedie.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 group-anagrams/Chaedie.py diff --git a/group-anagrams/Chaedie.py b/group-anagrams/Chaedie.py new file mode 100644 index 000000000..43d3e29d7 --- /dev/null +++ b/group-anagrams/Chaedie.py @@ -0,0 +1,22 @@ +""" +Solution: + 1) hash map 에 sorted_word를 키로, 해당 sorted_word 에 해당하는 요소들을 밸류로 넣습니다. +Time: O(n^2 logn)= O(n) * O(nlogn) +Space: O(n) +""" + + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + anagram_words = defaultdict(list) + # dict = {sorted_word: [word, word]} + + for i in range(len(strs)): + word = strs[i] + sorted_word = "".join(sorted(word)) + anagram_words[sorted_word].append(word) + + result = [] + for arr in anagram_words.values(): + result.append(arr) + return result