This solution is not done yet. I didn't check the validation of DAG.
#include <vector>
#include <string>
#include <iostream>
#include <stack>
#include <unordered_map>
#include <unordered_set>
using namespace std;
/*
There is a new alien language which uses the latin alphabet. However, the order among letters
are unknown to you. You receive a list of words from the dictionary, where words are sorted
lexicographically by the rules of this new language. Derive the order of letters in this language.
For example:
Given the following words in the dictionary.
["wrt", "wrf", "er", "ett", "rftt"] the correct order is "wertf"
Note:
You may assume all letters are in lowercase
If the order is invalid, return an emtpy string
There may be multiple valid order of letters, return any one of them is fine.
*/
// this is to apply topological sort, But, we need to build graph first.
void dfs(unordered_map<char, bool>& visited, unordered_map<char, unordered_set<char> >& charSequence, stack<char>& res, char tmp) {
visited[tmp] = true;
unordered_set<char> edges = charSequence[tmp];
auto iter = edges.begin();
while(iter != edges.end()) {
if(!visited[*iter]) {
dfs(visited, charSequence, res, *iter);
}
iter++;
}
res.push(tmp);
}
string alienOrder(vector<string> words) {
if(words.size() == 0) return "";
unordered_map<char, unordered_set<char> > charSequence;
unordered_set<char> chars;
for(int i = 0; i < words.size(); ++i) {
for(int j = 0; j < words[i].size(); ++j) {
chars.insert(words[i][j]);
}
for(int j = 0; j < words[i].size() - 1; ++j) {
for(int k = j + 1; k < words[i].size(); ++k) {
if(words[i][j] == words[i][k]) continue; // if the prev and next char is repeat, skip it.
charSequence[words[i][j]].insert(words[i][k]); // it is important here to use unordered_set to kick out repeats.
}
}
}
// building of DAG is done now.
int n = chars.size();
unordered_map<char, bool> visited;
auto iter = chars.begin();
while(iter != chars.end()) {
visited[*iter] = false;
iter++;
}
stack<char> res;
iter = chars.begin();
while(iter != chars.end()) {
if(!visited[*iter]) {
dfs(visited, charSequence, res, *iter);
}
iter++;
}
string result = "";
while(!res.empty()) {
char tmp = res.top();
result += tmp;
res.pop();
}
return result;
}
int main(void) {
vector<string> words{"wrt", "wrf", "er", "ett", "rftt"};
string res = alienOrder(words);
cout << res << endl;
}