|
| 1 | +/** |
| 2 | + * ๋ฌธ์ ์ค๋ช
|
| 3 | + * - ์ฃผ์ด์ง ๋จ์ด๋ค์ ํ์ฉํ์ฌ ์ํ๋ฒณ ์์๋ฅผ ์ฐพ๋ ๋ฌธ์ |
| 4 | + * |
| 5 | + * ์์ด๋์ด |
| 6 | + * 1) ์์์ ๋ ฌ (๐ ๋ค์์ ๋ค์ํ์ด๋ณด๊ธฐ) - Kahn's Algorithm |
| 7 | + * - ์ด๋ ต๋ค... |
| 8 | + */ |
| 9 | +function alienOrder(words: string[]): string { |
| 10 | + const graph: Map<string, Set<string>> = new Map(); |
| 11 | + const inDegree: Map<string, number> = new Map(); // ๊ฐ์ ์ ๊ฐฏ์(์ฒซ ์์์ด ๋ฌด์์ธ์ง ํ๋จํ๊ธฐ ์ํจ) |
| 12 | + |
| 13 | + // ๋จ์ด๋ค์ ๋์ค๋ ๋ชจ๋ ๋ฌธ์๋ฅผ ์ ๋ฆฌ ๋ฐ ์ด๊ธฐํ |
| 14 | + for (const word of words) { |
| 15 | + for (const char of word) { |
| 16 | + if (!graph.has(char)) { |
| 17 | + graph.set(char, new Set()); |
| 18 | + inDegree.set(char, 0); |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + // ๋จ์ด๋ค์ ๋น๊ตํด์ ์ํ๋ฒณ ๊ฐ์ ์ฐ์ ์์(๊ทธ๋ํ์ ๊ฐ์ ) ์ถ์ถ |
| 24 | + for (let i = 0; i < words.length - 1; i++) { |
| 25 | + const w1 = words[i]; |
| 26 | + const w2 = words[i + 1]; |
| 27 | + const minLen = Math.min(w1.length, w2.length); |
| 28 | + |
| 29 | + let foundDiff = false; |
| 30 | + |
| 31 | + for (let j = 0; j < minLen; j++) { |
| 32 | + const c1 = w1[j]; |
| 33 | + const c2 = w2[j]; |
| 34 | + if (c1 !== c2) { |
| 35 | + if (!graph.get(c1)!.has(c2)) { |
| 36 | + graph.get(c1)!.add(c2); |
| 37 | + inDegree.set(c2, inDegree.get(c2)! + 1); |
| 38 | + } |
| 39 | + foundDiff = true; |
| 40 | + break; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // ์ฌ์ ์์ด ์๋ ๊ฒฝ์ฐ ๋น๋ฌธ์์ด ๋ฆฌํด(If the order is invalid, return an empty string.) |
| 45 | + if (!foundDiff && w1.length > w2.length) return ""; |
| 46 | + } |
| 47 | + |
| 48 | + // BFS ์์์ ๋ ฌ ์์ |
| 49 | + const queue: string[] = []; |
| 50 | + for (const [char, degree] of inDegree.entries()) { |
| 51 | + if (degree === 0) queue.push(char); |
| 52 | + } |
| 53 | + |
| 54 | + const result: string[] = []; |
| 55 | + while (queue.length > 0) { |
| 56 | + const current = queue.shift()!; |
| 57 | + result.push(current); |
| 58 | + |
| 59 | + for (const neighbor of graph.get(current)!) { |
| 60 | + inDegree.set(neighbor, inDegree.get(neighbor)! - 1); |
| 61 | + if (inDegree.get(neighbor) === 0) { |
| 62 | + queue.push(neighbor); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return result.length === inDegree.size ? result.join("") : ""; |
| 68 | +} |
0 commit comments