-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0269-alien-dictionary.cpp
58 lines (53 loc) · 1.35 KB
/
0269-alien-dictionary.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
#include<iostream>
#include<map>
#include<vector>
#include<queue>
using namespace std;
class Solution {
public:
string alienOrder(vector<string>& words) {
map<char,int> degree;
map<char, vector<char>> graph;
int n = words.size();
for (auto& word : words) {
for (auto& ch : word) {
degree[ch] = 0;
}
for (int i = 0; i < n - 1; i++) {
int l = min((int)words[i].size(), (int)words[i + 1].size());
for (int j = 0; j < l; j++) {
char x = words[i][j];
char y = words[i + 1][j];
if (x != y) {
graph[x].push_back(y);
degree[y]++;
break;
}
}
}
string ret = "";
queue<char> q;
map<char, int>::iterator it = degree.begin();
while (it != degree.end()) {
if (it->second == 0) {
q.push(it->first);
}
it++;
}
while (!q.empty()) {
char x = q.front();
q.pop();
ret += x;
vector<char>::iterator sit = graph[x].begin();
while (sit != graph[x].end()) {
degree[*sit]--;
if (degree[*sit] == 0) {
q.push(*sit);
}
sit++;
}
}
return ret.size() == degree.size() ? ret : "";
}
}
};