nikunjsoni

269

Jun 1st, 2021
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string alienOrder(vector<string>& words) {
  4.         if(words.size() == 0) return "";
  5.         unordered_map<char, int> indegree;
  6.         unordered_map<char, unordered_set<char>> graph;
  7.        
  8.         // initialize
  9.         for(int i = 0; i < words.size(); i++) {
  10.             for(int j = 0; j < words[i].size(); j++) {
  11.                 char c = words[i][j];
  12.                 indegree[c] = 0;
  13.             }
  14.         }
  15.        
  16.         //Build graph and store indegree.
  17.         for(int i = 0; i < words.size() - 1; i++) {
  18.             string cur = words[i];
  19.             string nex = words[i + 1];
  20.             int len = min(cur.size(), nex.size());
  21.             if(cur.length() > nex.length() && !cur.find(nex))
  22.                 return "";
  23.             for(int j = 0; j < len; j++) {
  24.                 if(cur[j] != nex[j]) {
  25.                     int sz1 = graph[cur[j]].size();
  26.                     graph[cur[j]].insert(nex[j]); // build graph
  27.                     int sz2 = graph[cur[j]].size();
  28.                     if(sz1 != sz2)
  29.                         indegree[nex[j]]++; // add indegree
  30.                     break;                        
  31.                 }
  32.             }
  33.         }
  34.        
  35.         //Topo sort using BFS.
  36.         string ans;
  37.         queue<char> q;
  38.         for(auto& e : indegree)
  39.             if(e.second == 0)
  40.                 q.push(e.first);
  41.        
  42.         while(!q.empty()) {
  43.             char cur = q.front();
  44.             q.pop();
  45.             ans += cur;
  46.             for(auto& e : graph[cur])
  47.                 if(--indegree[e] == 0)
  48.                     q.push(e);
  49.         }
  50.        
  51.         //If cyclic, return empty string.
  52.         return ans.length() == indegree.size() ? ans : "";
  53.     }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment