-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlienDict.cpp
More file actions
77 lines (61 loc) · 1.98 KB
/
Copy pathAlienDict.cpp
File metadata and controls
77 lines (61 loc) · 1.98 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
66
67
68
69
70
71
72
73
74
75
76
77
/*
Given a sorted dictionary of an alien language having N words and k starting alphabets of standard dictionary.
Find the order of characters in the alien language.
Note: Many orders may be possible for a particular test case, thus you may return any valid order
and output will be 1 if the order of string returned by the function is correct
else 0 denoting incorrect string returned.
Input:
N = 5, K = 4
dict = {"baa","abcd","abca","cab","cad"}
Output:
1
Explanation:
Here order of characters is
'b', 'd', 'a', 'c' Note that words are sorted
and in the given language "baa" comes before
"abcd", therefore 'b' is before 'a' in output.
Similarly we can find other orders.
*/
class Solution
{
public:
void toposort(int node, unordered_map<int,vector<int>> &adjList, vector<bool> &visited, string &ans)
{
visited[node] = 1;
for(auto i:adjList[node])
{
if(!visited[i]) toposort(i,adjList,visited,ans);
}
ans = (char)(node+'a') + ans;
}
string findOrder(string dict[], int N, int K)
{
unordered_map<int, vector<int> > adjList;
for(int i=0;i<N-1;i++)
{
string word1 = dict[i];
string word2 = dict[i+1];
for(int j=0;j<min(word1.length(),word2.length());j++)
{
if(word1[j]!=word2[j])
{
adjList[word1[j]-'a'].push_back(word2[j]-'a');
break;
}
}
}
// for(auto i:adjList)
// {
// cout<<(char)(i.first + 'a')<<"-->";
// for(auto j:adjList[i.first]) cout<<(char)(j+'a')<<",";
// cout<<endl;
// }
string ans = "";
vector<bool> visited(K,0);
for(int i=0;i<K;i++)
{
if(!visited[i]) toposort(i,adjList,visited,ans);
}
return ans;
}
};