Skip to content

Commit 2c6b6f3

Browse files
committed
feat(soobing): week15 > alien-dictionary
1 parent f075676 commit 2c6b6f3

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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

Comments
ย (0)