-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforeign-dictionary.cpp
More file actions
65 lines (64 loc) · 1.84 KB
/
Copy pathforeign-dictionary.cpp
File metadata and controls
65 lines (64 loc) · 1.84 KB
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
//https://neetcode.io/problems/foreign-dictionary
class Solution {
public:
void update(unordered_map<char, unordered_set<char>> &m, string str1, string str2){
int len = min((int)str1.size(), (int)str2.size());
for(int i=0; i<len; i++){
if(str1[i] != str2[i]){
m[str1[i]].insert(str2[i]);
return;
}
}
if(str1.size() > str2.size())
m.clear();
}
string bfs(unordered_map<char, int> &m_indegree, unordered_map<char, unordered_set<char>> &m){
queue<char> q;
for(auto a: m_indegree){
if(a.second == 0)
q.push(a.first);
}
string res = "";
while(!q.empty()){
char ch = q.front();
q.pop();
res += ch;
for(auto next: m[ch]){
m_indegree[next]--;
if(m_indegree[next] == 0){
q.push(next);
}
}
}
if(res.size() != m_indegree.size())
return "";
return res;
}
string foreignDictionary(vector<string>& words) {
unordered_map<char, unordered_set<char>> m;
for(auto word: words){
for(auto ch: word){
m[ch];
}
}
for(int i=0; i<words.size()-1; i++){
update(m, words[i], words[i+1]);
if(m.empty())
return "";
}
unordered_map<char, int> m_indegree;
for(auto a: m){
if(!m_indegree.count(a.first))
m_indegree[a.first] = 0;
for(auto next: a.second){
m_indegree[next]++;
}
}
return bfs(m_indegree, m);
}
};
["ab", "adc", "bd"]
["wrt", "wrf", "er", "ett", "rftt"]
["z", "x", "z"]
["abc", "ab"]
["qwer", "qwrt", "qwe", "qwet"]