forked from codewithshailendra/COYO-IIT-BHU
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlien Dictionary
65 lines (50 loc) · 1.09 KB
/
Alien Dictionary
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
string printOrder(string dict[], int N, int k)
{
map<char,vector<char> >mp;
map<char,int>check;
for(int i=0;i<N-1;i++)
{
string s1=dict[i];
string s2=dict[i+1];
for(int i=0;i<min(s1.length(),s2.length());i++)
{
check[s1[i]]++;
check[s2[i]]++;
if(s1[i]!=s2[i])
{
mp[s1[i]].push_back(s2[i]);
break;
}
}
}
map<char,int>indegree;
for(auto x:check)
{
indegree[x.first]=0;
}
for(auto x:mp)
{
for(auto y:x.second)
{
indegree[y]++;
}
}
string ans;
queue<char>q;
for(auto x:indegree)
if(x.second==0)
q.push(x.first);
while(!q.empty())
{
char ch=q.front();
q.pop();
ans+=ch;
for(auto x:mp[ch])
{
indegree[x]--;
if(indegree[x]==0)
q.push(x);
}
}
return ans;
}