-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path269 AlienDictionary.cpp
63 lines (49 loc) · 1.63 KB
/
269 AlienDictionary.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
class Solution {
public:
unordered_map<char, vector<char>> graph; // Could use 2D vector for adjacency list
unordered_map<char, int> visited;
int orderNum;
void explore(const char& v) {
visited[v];
for(const char& e : graph[v]) {
if(visited.find(e) == visited.end())
explore(e);
}
visited[v] = --orderNum;
}
string foreignDictionary(vector<string>& words) {
for(const string& s : words) { // Create vertices
for(const char& c : s)
graph[c];
}
for(int i = 0; i < words.size() - 1; ++i) { // Create edges
bool earlyBreak = false;
for(int j = 0; j < words[i].length() && j < words[i + 1].length(); ++j) {
char a = words[i][j], b = words[i + 1][j];
if(a != b) {
graph[a].push_back(b);
earlyBreak = true;
break;
}
}
if(!earlyBreak && words[i].length() > words[i + 1].length())
return "";
}
orderNum = graph.size();
visited.reserve(orderNum);
string s(orderNum, ' ');
for(const auto& v : graph) { // DFS
if(visited.find(v.first) == visited.end())
explore(v.first);
}
for(const auto& v : graph) { // Check for cycles
for(const char& c : v.second) {
if(visited[v.first] > visited[c])
return "";
}
}
for(const auto& v : visited)
s[v.second] = v.first;
return s;
}
};