Skip to content

Commit 8154a14

Browse files
committed
Solved "Group Anagrams"
1 parent 6ca4a28 commit 8154a14

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
Constraints:
3+
1. 1 <= strs.length <= 10^4
4+
2. 0 <= strs[i].length <= 100
5+
3. strs[i] consists of lowercase English letters.
6+
7+
Time Complexity: O(N * K * log K)
8+
- N์€ ์ž…๋ ฅ ๋ฌธ์ž์—ด์˜ ๊ฐœ์ˆ˜ (strs์˜ ๊ธธ์ด)
9+
- K๋Š” ๊ฐ€์žฅ ๊ธด ๋ฌธ์ž์—ด์˜ ๊ธธ์ด
10+
- ๊ฐ ๋ฌธ์ž์—ด์„ ์ •๋ ฌํ•˜๋Š”๋ฐ K * log K๊ฐ€ ํ•„์š”ํ•˜๊ณ 
11+
- ์ด๊ฑธ N๊ฐœ์˜ ๋ฌธ์ž์—ด์— ๋Œ€ํ•ด ์ˆ˜ํ–‰
12+
13+
Space Complexity: O(N * K)
14+
- N๊ฐœ์˜ ๋ฌธ์ž์—ด์„ ์ €์žฅํ•ด์•ผ ํ•จ
15+
- ๊ฐ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” ์ตœ๋Œ€ K
16+
- anagram_dict์— ๋ชจ๋“  ๋ฌธ์ž์—ด์„ ์ €์žฅํ•˜๊ธฐ ๋•Œ๋ฌธ
17+
"""
18+
19+
class Solution:
20+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
21+
anagram_dict = {}
22+
23+
for s in strs:
24+
sorted_str = ''.join(sorted(s))
25+
26+
if sorted_str in anagram_dict:
27+
anagram_dict[sorted_str].append(s)
28+
else:
29+
anagram_dict[sorted_str] = [s]
30+
31+
return list(anagram_dict.values())

0 commit comments

Comments
ย (0)