LCR 114. 火星词典
使用拓扑排序就可以,有一个实例需要考虑特殊情况
cpp
class Solution {
public:
string alienOrder(vector<string>& words) {
unordered_map<char,unordered_set<char>> graph;
unordered_map<char,int> inorder;
int n = words.size();
for(int i=0;i<n;++i){
for(int k=0;k<words[i].size();++k){
inorder[words[i][k]] = 0;
}
}
bool special = true;
//建图
for(int i=0;i<n;++i){
for(int j=i+1;j<n;++j){
special = true;
for(int k=0;k<min(words[i].size(),words[j].size());++k){
if(words[i][k] != words[j][k]){
if(!graph[words[i][k]].count(words[j][k])){
graph[words[i][k]].insert(words[j][k]);
inorder[words[j][k]]++;
}
special = false;
break;
}
}
if(special && words[i].size() > words[j].size()){
return "";
}
}
}
queue<char> que;
for(auto [u,v]:inorder){
if(v == 0){
que.push(u);
}
}
string ret = "";
while(!que.empty()){
auto t = que.front();
que.pop();
ret = ret + t;
for(auto e : graph[t]){
inorder[e]--;
if(inorder[e] == 0){
que.push(e);
}
}
}
if(ret.size() != inorder.size()){
return "";
}
return ret;
}
};