-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlien Dictionary.cpp
50 lines (43 loc) · 1.1 KB
/
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
class Solution{
public:
string findOrder(string dict[], int N, int K) {
vector<int> adj[K];
for(int i=0;i<N-1;i++)
{
for(int j=0;j<min(dict[i].length(),dict[i+1].length());j++)
{
if(dict[i][j]!=dict[i+1][j])
{
adj[dict[i][j]-'a'].push_back(dict[i+1][j]-'a');
break;
}
}
}
vector<int> indegree(K,0);
for(int i=0;i<K;i++)
{
for(auto it:adj[i])
indegree[it]++;
}
queue<int> q;
for(int i=0;i<K;i++)
{
if(indegree[i]==0)
q.push(i);
}
string ans="";
while(!q.empty())
{
int front=q.front();
ans+=char((front+97));
q.pop();
for(auto it:adj[front])
{
indegree[it]--;
if(indegree[it]==0)
q.push(it);
}
}
return ans;
}
};