Skip to content

Commit bd232b4

Browse files
committed
docs: Improve docstring and comments for groupAnagrams method
1 parent 88ba4c1 commit bd232b4

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

โ€Žgroup-anagrams/river20s.py

+19-1
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,27 @@ def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
66
"""
77
:type strs: List[str]
88
: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๊ฐœ๊ฐ€ ๋ชจ๋‘ ์ €์žฅ๋จ
916
"""
17+
# collections์˜ defaultdict ์‚ฌ์šฉํ•˜์—ฌ Key ์—†์„ ๋•Œ ์ž๋™์œผ๋กœ ๋นˆ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑํ•จ
18+
# Key: ์ •๋ ฌ๋œ ๋ฌธ์ž์—ด, Value: ์›๋ž˜ ๋ฌธ์ž์—ด์˜ ๋ฆฌ์ŠคํŠธ
1019
anagram_groups = collections.defaultdict(list)
20+
21+
# s๋Š” ์ž…๋ ฅ strs์˜ ๊ฐ ๋ฌธ์ž์—ด
22+
# ๋ชจ๋“  s์— ๋Œ€ํ•ด ์ˆœํšŒ
1123
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 ์ถ”๊ฐ€
1330
anagram_groups[key].append(s)
31+
# ๋”•์…”๋„ˆ๋ฆฌ Value๋งŒ ๋ชจ์•„ ๋ฐ˜ํ™˜
1432
return list(anagram_groups.values())

0 commit comments

Comments
ย (0)