@@ -6,9 +6,27 @@ def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
6
6
"""
7
7
:type strs: List[str]
8
8
:rtype: List[List[str]]
9
+ ๊ฐ ๋ฌธ์์ด์ ์ํํ๋ฉด์ ์ํ๋ฒณ ์์ผ๋ก ์ ๋ ฌํ ๊ฒฐ๊ณผ๋ฅผ tuple๋ก ๋ณํํ์ฌ Key๋ก ํ๊ณ ,
10
+ ๊ทธ Key์ ์๋ ๋ฌธ์์ด์ Value๋ก ํ๋ ๋์
๋๋ฆฌ๋ฅผ ํตํด ์ ๋๊ทธ๋จ์ ๊ทธ๋ฃนํ ํ๋ ๋ฌธ์
11
+ ๋์
๋๋ฆฌ์ Value๋ง ๋ชจ์์ ๋ฐํํจ
12
+ Time Complexity: O(N*K log K) (๋จ, N์ ์
๋ ฅ ๋ฆฌ์คํธ ์์ ๋ฌธ์์ด ๊ฐ์(๋ฆฌ์คํธ ๊ธธ์ด), K๋ ๋ฌธ์์ด ํ๋ ๋น ๊ธธ์ด)
13
+ -> ์ ๋ ฌ์ O(K log K)์๊ฐ ์์, ์ ๋ ฌ ์์
์ ๋ฆฌ์คํธ ์์ ๋ฌธ์์ด ๊ฐ์ N๋งํผ ๋ฐ๋ณต
14
+ Space Complexity: O(N*K)
15
+ -> ๋์
๋๋ฆฌ๋ฅผ ํตํด ์๋ณธ ๋ฌธ์์ด N๊ฐ๊ฐ ๋ชจ๋ ์ ์ฅ๋จ
9
16
"""
17
+ # collections์ defaultdict ์ฌ์ฉํ์ฌ Key ์์ ๋ ์๋์ผ๋ก ๋น ๋ฆฌ์คํธ ์์ฑํจ
18
+ # Key: ์ ๋ ฌ๋ ๋ฌธ์์ด, Value: ์๋ ๋ฌธ์์ด์ ๋ฆฌ์คํธ
10
19
anagram_groups = collections .defaultdict (list )
20
+
21
+ # s๋ ์
๋ ฅ strs์ ๊ฐ ๋ฌธ์์ด
22
+ # ๋ชจ๋ s์ ๋ํด ์ํ
11
23
for s in strs :
12
- key = tuple (sorted (s ))
24
+ # s๋ฅผ ์ํ๋ฒณ ์์ผ๋ก ์ ๋ ฌํ๊ณ , Key๋ก ์ฐ๊ธฐ ์ํด ํํ๋ก ๋ณํํจ
25
+ # sorted(s)๋ ๊ฐ ๋ฌธ์๋ฅผ ์์๋ก ๊ฐ๋ ๋ฆฌ์คํธ(์: ['h', 'i'])
26
+ # ํํ๋ก ๋ฐ๊ฟ์ Key๋ก ์ธ ์ ์๊ฒ ํ์์
27
+ key = tuple (sorted (s ))
28
+ # defaultdict ์ฌ์ฉํ๋ฏ๋ก, Key ์กด์ฌ ์ฌ๋ถ ํ์ธ ๋ถํ์
29
+ # ํด๋น Key์ Value์ ์๋ ๋ฌธ์์ด s ์ถ๊ฐ
13
30
anagram_groups [key ].append (s )
31
+ # ๋์
๋๋ฆฌ Value๋ง ๋ชจ์ ๋ฐํ
14
32
return list (anagram_groups .values ())
0 commit comments