题面:
题解:按照拓扑序即可。
代码:
class Solution { public: string alienOrder(vector<string>& words) { int n = words.size(); string ans=""; unordered_map<char, unordered_set<int> >g; unordered_map<char, int> d; string s1, s2; int n1, n2; for(int i = 0;i < n;i ++) { for(auto t: words[i]) d[t]=0; } for(int i = 1;i < n;i ++) { s1 = words[i - 1]; s2 = words[i]; n1 = s1.size(); n2 = s2.size(); int j; for(j = 0;j < min(n1, n2); j++) { if(s1[j] != s2[j]) { if(g[s1[j]].find(s2[j])==g[s1[j]].end()) { d[s2[j]] ++; g[s1[j]].insert(s2[j]); } break; } } if(j == min(n1, n2)&&n1>n2)return ""; } queue< char >q; for(auto t : d) { auto c = t.first; if(!d[c]) { q.push(c); } } while(q.size()) { auto u = q.front(); q.pop(); ans += u; for(auto t: g[u]) { d[t]--; if(!d[t]) { q.push(t); } } } //cout<<ans<<endl; if(ans.size() != d.size())return ""; return ans; } };