Alien Dictionary Posted on 2018-10-10 Descriptionhttps://leetcode.com/problems/alien-dictionary/description/ Solution12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970class Solution {public: void extractRules(string& word1, string& word2, unordered_map<char, unordered_set<char>>& rules, unordered_map<char, int>& counter) { int index = 0; int bound = min(word1.size(), word2.size()); while(index < bound && word1[index] == word2[index]) { ++index; } if (index == bound) return; char left = word1[index]; char right = word2[index]; if(rules[left].find(right) == rules[left].end()) { rules[left].insert(right); ++counter[right]; } } void fillCharacter(unordered_map<char, int>& counter, vector<string>& words) { for (string& word : words) { for(int index = 0; index < word.size(); ++index) { if (counter.count(word[index]) == 0) counter[word[index]] = 0; } } } string alienOrder(vector<string>& words) { int size = words.size(); string ret; if (size == 0) return ret; unordered_map<char, unordered_set<char>> rules; unordered_map<char, int> counter; fillCharacter(counter, words); for (int i = 0; i < size - 1; ++i){ for (int j = i + 1; j < size; ++j) { string& word1 = words[i]; string& word2 = words[j]; extractRules(word1, word2, rules, counter); } } queue<char> que; for (auto iter = counter.begin(); iter != counter.end(); ++iter) { if (iter->second == 0) { ret += iter->first; que.push(iter->first); } } while (!que.empty()) { char c = que.front(); que.pop(); unordered_set<char>& follows = rules[c]; for (char ch : follows) { --counter[ch]; if (counter[ch] == 0) { ret += ch; que.push(ch); } } } for (auto& iter : counter) if (iter.second != 0) return string(); return ret; }};