|
| 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