-
Notifications
You must be signed in to change notification settings - Fork 130
/
Alien Dictionary.js
97 lines (78 loc) · 2.43 KB
/
Alien Dictionary.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
For example,
Given the following words in dictionary,
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
The correct order is: "wertf".
Note:
You may assume all letters are in lowercase.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.
*/
/**
* @param {string[]} words
* @return {string}
*/
var alienOrder = function(words) {
if (words.length === 0) {
return '';
}
const len = words.length;
let map = {}; // value is the prerequisite of key
let charPreReqCount = {};
let i;
let queue = [];
let result = [];
let hasCycle = false;
for (i = 0; i < len; i++) {
const chars = words[i].split('');
let j = 0;
for (j = 0; j < chars.length; j++) {
if (!map[chars[j]]) {
map[chars[j]] = [];
charPreReqCount[chars[j]] = 0;
}
}
if (i === 0 || words[i] === words[i - 1]) {
continue;
}
const cur = words[i];
const prev = words[i - 1];
j = 0;
while(j < cur.length && j < prev.length && cur.charAt(j) === prev.charAt(j)) {
j++;
}
if (j < prev.length && map[prev.charAt(j)].indexOf(cur.charAt(j)) === -1) {
map[prev.charAt(j)].push(cur.charAt(j));
charPreReqCount[cur.charAt(j)]++;
}
}
Object.keys(charPreReqCount).forEach(char => {
if (charPreReqCount[char] === 0) {
queue.push(char);
}
});
while(queue.length > 0) {
const char = queue.shift();
result.push(char);
for (i = 0; i < map[char].length; i++) {
charPreReqCount[map[char][i]]--;
if (charPreReqCount[map[char][i]] === 0) {
queue.push(map[char][i]);
}
}
}
// detect cycle
Object.keys(charPreReqCount).forEach(function(char) {
if (charPreReqCount[char] !== 0) {
hasCycle = true;
}
});
return hasCycle ? '' : result.join('');
};