This repository has been archived by the owner on May 16, 2021. It is now read-only.
forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalien-dictionary_1_AC.cpp
81 lines (74 loc) · 1.87 KB
/
alien-dictionary_1_AC.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
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
// Topological sort
// Number of nodes is too small, so don't bother with heap optimization.
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using std::make_pair;
using std::pair;
using std::string;
using std::unordered_map;
using std::unordered_set;
using std::vector;
class Solution {
public:
string alienOrder(vector<string>& words) {
auto &w = words;
int n = w.size();
unordered_map<char, unordered_set<char>> g;
unordered_map<char, int> ind;
for (auto &s: w) {
for (auto &ch: s) {
g[ch];
ind[ch] = 0;
}
}
int m = ind.size();
int ls, lt;
int i, j;
for (i = 0; i + 1 < n; ++i) {
string &s = w[i];
string &t = w[i + 1];
ls = s.size();
lt = t.size();
for (j = 0; j < ls && j < lt; ++j) {
if (s[j] == t[j]) {
continue;
}
if (g[s[j]].find(t[j]) == g[s[j]].end()) {
g[s[j]].insert(t[j]);
++ind[t[j]];
}
break;
}
}
char ch;
string res = "";
while (true) {
ch = '\0';
for (auto &p: ind) {
if (p.second == 0) {
ch = p.first;
break;
}
}
if (ch == '\0') {
break;
}
for (auto &ch1: g[ch]) {
--ind[ch1];
}
g.erase(ch);
ind.erase(ch);
res.push_back(ch);
--m;
}
if (m > 0) {
res = "";
}
g.clear();
ind.clear();
return res;
}
};