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
const int N = 26, M = N * N;

class Solution {
public:
int cnt = 0;
bool st[N];
int h[N], e[M], ne[M], in[N], out[N], idx;
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
out[a]++;
in[b]++;
}
string alienOrder(vector<string>& words) {
memset(h, -1, sizeof h);
memset(st, 0, sizeof st);
int n = words.size();
for (int i = 0; i < n; i++) {
for (auto& c : words[i]) {
if (!st[c - 'a'] && ++cnt >= 0) st[c - 'a'] = true;
}
for (int j = 0; j < i; j++) {
if (!build(words[j], words[i])) return "";
}
}
queue<int> q;
// 将入度为 0 的节点放入队列
for (int i = 0; i < 26; i++) {
if (st[i] && in[i] == 0) q.push(i);
}
string s;
// 拓扑排序
while (q.size()) {
int u = q.front();
q.pop();
s += u + 'a';
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (--in[j] == 0) q.push(j);
}
}
return s.size() == cnt ? s : "";
}
bool build(string a, string b) {
int n = a.size(), m = b.size(), len = min(n, m);
for (int i = 0; i < len; i++) {
int c1 = a[i] - 'a', c2 = b[i] - 'a';
if (c1 != c2) {
add(c1, c2);
return true;
}
}
return n <= m;
}
};