|
| 1 | +/** |
| 2 | + * |
| 3 | + * @problem |
| 4 | + * ๋ฌธ์์ด ๋ฐฐ์ด์ด ์ฃผ์ด์ก์ ๋, ์ ๋๊ทธ๋จ๋ผ๋ฆฌ ๊ทธ๋ฃนํํด์ผ ํฉ๋๋ค. |
| 5 | + * |
| 6 | + * (์ฐธ๊ณ ) |
| 7 | + * ์ ๋๊ทธ๋จ(Anagram)์ด๋ ๋จ์ด๋ฅผ ๊ตฌ์ฑํ๋ ๋ฌธ์์ ์์๋ฅผ ๋ฐ๊ฟ์ ๋ค๋ฅธ ๋จ์ด๋ฅผ ๋ง๋๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค. |
| 8 | + * ์๋ฅผ ๋ค์ด, "eat", "tea", "ate"๋ ๋ชจ๋ ๊ฐ์ ๋ฌธ์๋ก ๊ตฌ์ฑ๋์ด ์์ผ๋ฏ๋ก ์ ๋๊ทธ๋จ์
๋๋ค. |
| 9 | + * |
| 10 | + * @param {string[]} strs - ์
๋ ฅ ๋ฌธ์์ด ๋ฐฐ์ด |
| 11 | + * @returns {string[][]} ์ ๋๊ทธ๋จ ๊ทธ๋ฃน์ผ๋ก ๋ฌถ์ธ 2์ฐจ์ ๋ฌธ์์ด ๋ฐฐ์ด |
| 12 | + * |
| 13 | + * @example |
| 14 | + * groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]); // [["bat"], ["nat", "tan"], ["ate", "eat", "tea"]] |
| 15 | + * groupAnagrams([""]); // [[""]] |
| 16 | + * groupAnagrams(["a"]); // [["a"]] |
| 17 | + * |
| 18 | + * @description |
| 19 | + * - ์๊ฐ ๋ณต์ก๋: O(N * K log K) |
| 20 | + * ใด N: ์
๋ ฅ ๋ฌธ์์ด ๋ฐฐ์ด์ ๊ธธ์ด |
| 21 | + * ใด K: ๊ฐ ๋ฌธ์์ด์ ํ๊ท ๊ธธ์ด |
| 22 | + * ๊ฐ ๋ฌธ์์ด์ ์ ๋ ฌํ๋ ๋ฐ O(K log K)์ ์๊ฐ์ด ์์๋๋ฉฐ, ์ด๋ฅผ N๋ฒ ๋ฐ๋ณตํฉ๋๋ค. |
| 23 | + * - ๊ณต๊ฐ ๋ณต์ก๋: O(N * K) |
| 24 | + * ํด์๋งต์ ์ ์ฅ๋๋ ํค์ ๊ฐ์ ์ด ๊ธธ์ด์ ๋น๋กํฉ๋๋ค. |
| 25 | + */ |
| 26 | +function groupAnagrams(strs: string[]): string[][] { |
| 27 | + // ์ ๋๊ทธ๋จ ๊ทธ๋ฃน์ ์ ์ฅํ ํด์๋งต |
| 28 | + const anagrams: Record<string, string[]> = {}; |
| 29 | + |
| 30 | + // ์
๋ ฅ ๋ฌธ์์ด ๋ฐฐ์ด์ ์ํ |
| 31 | + for (const str of strs) { |
| 32 | + // ๋ฌธ์์ด์ ์ ๋ ฌํ์ฌ ์ ๋๊ทธ๋จ ๊ทธ๋ฃน์ ํค ์์ฑ |
| 33 | + const key = str.split('').sort().join(''); |
| 34 | + |
| 35 | + // ํค๊ฐ ํด์๋งต์ ์์ผ๋ฉด ์ด๊ธฐํ |
| 36 | + if (!anagrams[key]) { |
| 37 | + anagrams[key] = []; |
| 38 | + } |
| 39 | + |
| 40 | + // ํด๋น ํค์ ๋ฌธ์์ด ์ถ๊ฐ |
| 41 | + anagrams[key].push(str); |
| 42 | + } |
| 43 | + |
| 44 | + // ํด์๋งต์ ๊ฐ๋ค๋ง ๋ฐํ (์ ๋๊ทธ๋จ ๊ทธ๋ฃน) |
| 45 | + return Object.values(anagrams); |
| 46 | +} |
| 47 | + |
| 48 | +console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])); // [["bat"], ["nat", "tan"], ["ate", "eat", "tea"]] |
| 49 | +console.log(groupAnagrams([""])); // [[""]] |
| 50 | +console.log(groupAnagrams(["a"])); // [["a"]] |
0 commit comments