Skip to content

Commit 89a79b3

Browse files
authored
[ PS ] : Alien Dictionary
1 parent a16a983 commit 89a79b3

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

โ€Žalien-dictionary/uraflower.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/**
2+
* @param words: a list of words
3+
* @return: a string which is correct order
4+
*/
5+
const alienOrder = (words) => {
6+
const graph = {};
7+
8+
// ์ดˆ๊ธฐํ™”
9+
for (const word of words) {
10+
for (const char of word) {
11+
if (!graph[char]) {
12+
graph[char] = new Set();
13+
}
14+
}
15+
}
16+
17+
// ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ
18+
for (let i = 1; i < words.length; i++) {
19+
const prev = words[i - 1];
20+
const current = words[i];
21+
let found = false;
22+
23+
const minLen = Math.min(prev.length, current.length);
24+
for (let j = 0; j < minLen; j++) {
25+
graph[prev[j]].add(current[j]);
26+
}
27+
// ๋ชจ์ˆœ ์ฒ˜๋ฆฌ
28+
if (!found && prev.length > current.length) {
29+
return '';
30+
}
31+
}
32+
33+
// ํƒ์ƒ‰
34+
const output = [];
35+
const visiting = new Set();
36+
const visited = new Set();
37+
38+
function dfs(current) {
39+
if (visiting.has(current)) {
40+
return false;
41+
}
42+
if (visited.has(current)) {
43+
return true;
44+
}
45+
46+
visiting.add(current);
47+
for (const adj of graph[current]) {
48+
if (!dfs(adj)) {
49+
return false;
50+
}
51+
}
52+
visiting.delete(current);
53+
54+
visited.add(current);
55+
output.push(current);
56+
return true;
57+
}
58+
59+
// ์ˆœํšŒ
60+
for (const node in graph) {
61+
if (!dfs(node)) {
62+
return '';
63+
}
64+
}
65+
66+
return output.reverse().join('')
67+
}
68+
69+
70+
// ๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„๋กœ ์„ ํ–‰๋˜๋Š” ์ˆœ์„œ๋ฅผ ํ‘œํ˜„
71+
// ๋น„์Šทํ•œ ๋ฌธ์ œ: https://leetcode.com/problems/course-schedule/description/
72+
73+
// ์œ„์ƒ์ •๋ ฌ ์‚ฌ์šฉํ•ด์„œ ์ง„์ž…์ฐจ์ˆ˜ ๊ธฐ์ค€ ์ •๋ ฌํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ์Œ
74+
// ๋„ˆ๋ฌด ์–ด๋ ค์› ๋‹ค...

0 commit comments

Comments
ย (0)