Skip to content

Commit 5e0b8c0

Browse files
committed
grounp-anagram solution (py, ts)
1 parent ed2c4c4 commit 5e0b8c0

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

group-anagrams/hi-rachel.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# TC O(N * K log K), SC O(N * K)
2+
3+
from collections import defaultdict
4+
5+
class Solution:
6+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
7+
anagram_map = defaultdict(list)
8+
9+
for word in strs:
10+
key = ''.join(sorted(word))
11+
anagram_map[key].append(word)
12+
13+
return list(anagram_map.values())
14+

group-anagrams/hi-rachel.ts

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// TC O(N * K log K), N: 단어 수, K: 평균 단어 길이, 각 단어를 정렬
2+
// SC O(N * K)
3+
4+
/**
5+
* Array.from() => 이터러블 -> 일반 배열로 변환
6+
*/
7+
function groupAnagrams(strs: string[]): string[][] {
8+
const anagramMap: Map<string, string[]> = new Map();
9+
10+
for (const word of strs) {
11+
const key = word.split("").sort().join("");
12+
const group = anagramMap.get(key) || [];
13+
group.push(word);
14+
anagramMap.set(key, group);
15+
}
16+
return Array.from(anagramMap.values());
17+
}
18+
19+
/**
20+
* reduce 풀이
21+
*/
22+
// function groupAnagrams(strs: string[]): string[][] {
23+
// const anagramMap = strs.reduce((map, word) => {
24+
// const key = word.split("").sort().join("");
25+
// if (!map.has(key)) {
26+
// map.set(key, []);
27+
// }
28+
// map.get(key).push(word);
29+
// return map;
30+
// }, new Map<string, string[]>());
31+
32+
// return Array.from(anagramMap.values());
33+
// }
34+
35+
/** 간결한 버전
36+
* x ||= y (ES2021)
37+
* x가 falsy 값이면 y를 할당
38+
* JS에서 falsy 값 = false, 0, '', null, undefined, NaN
39+
*
40+
* Object.values() => 객체의 값들만 배열로 추출할때 사용
41+
*/
42+
// function groupAnagrams(strs: string[]): string[][] {
43+
// const anagramMap: {[key: string]: string[]} = {};
44+
45+
// strs.forEach((word) => {
46+
// const key = word.split('').sort().join('');
47+
// (anagramMap[key] ||= []).push(word);
48+
// });
49+
50+
// return Object.values(anagramMap);
51+
// }

0 commit comments

Comments
 (0)