File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ string alienOrder (vector<string> &words) {
4
+ // Write your code here
5
+ unordered_map<char , unordered_set<char >> graph;
6
+ unordered_map<char , int > indegree;
7
+ unordered_set<char > all_chars;
8
+
9
+ for (const string& word : words) {
10
+ for (char c : word) {
11
+ all_chars.insert (c);
12
+ if (!indegree.count (c))
13
+ indegree[c] = 0 ;
14
+ }
15
+ }
16
+
17
+ for (int i = 0 ; i < words.size () - 1 ; i++){
18
+ string word1 = words[i];
19
+ string word2 = words[i + 1 ];
20
+ int len = min (word1.size (), word2.size ());
21
+ bool found = false ;
22
+
23
+ for (int j = 0 ; j < len; j++){
24
+ char ch1 = word1[j];
25
+ char ch2 = word2[j];
26
+
27
+ if (ch1 != ch2){
28
+ if (graph[ch1].count (ch2) == 0 ){
29
+ graph[ch1].insert (ch2);
30
+ indegree[ch2]++;
31
+ }
32
+
33
+ found = true ;
34
+ break ;
35
+ }
36
+ }
37
+
38
+ if (!found && word1.size () > word2.size ())
39
+ return " " ;
40
+ }
41
+
42
+ queue<char > q;
43
+ for (char c : all_chars){
44
+ if (indegree[c] == 0 )
45
+ q.push (c);
46
+ }
47
+
48
+ string order;
49
+
50
+ while (!q.empty ()){
51
+ char cur = q.front ();
52
+ q.pop ();
53
+
54
+ order += cur;
55
+
56
+ for (char next : graph[cur]){
57
+ if (--indegree[next] == 0 )
58
+ q.push (next);
59
+ }
60
+ }
61
+
62
+ if (order.size () != all_chars.size ())
63
+ return " " ;
64
+
65
+ return order;
66
+ }
67
+ };
You can’t perform that action at this time.
0 commit comments