-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
56 lines (56 loc) · 1.7 KB
/
Solution.cpp
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
class Solution {
public:
string alienOrder(vector<string>& words) {
vector<vector<bool>> g(26, vector<bool>(26));
vector<bool> s(26);
int cnt = 0;
int n = words.size();
for (int i = 0; i < n - 1; ++i) {
for (char c : words[i]) {
if (cnt == 26) break;
c -= 'a';
if (!s[c]) {
++cnt;
s[c] = true;
}
}
int m = words[i].size();
for (int j = 0; j < m; ++j) {
if (j >= words[i + 1].size()) return "";
char c1 = words[i][j], c2 = words[i + 1][j];
if (c1 == c2) continue;
if (g[c2 - 'a'][c1 - 'a']) return "";
g[c1 - 'a'][c2 - 'a'] = true;
break;
}
}
for (char c : words[n - 1]) {
if (cnt == 26) break;
c -= 'a';
if (!s[c]) {
++cnt;
s[c] = true;
}
}
vector<int> indegree(26);
for (int i = 0; i < 26; ++i)
for (int j = 0; j < 26; ++j)
if (i != j && s[i] && s[j] && g[i][j])
++indegree[j];
queue<int> q;
for (int i = 0; i < 26; ++i)
if (s[i] && indegree[i] == 0)
q.push(i);
string ans = "";
while (!q.empty()) {
int t = q.front();
ans += (t + 'a');
q.pop();
for (int i = 0; i < 26; ++i)
if (i != t && s[i] && g[t][i])
if (--indegree[i] == 0)
q.push(i);
}
return ans.size() < cnt ? "" : ans;
}
};