[剑指 Offer II 114. 外星文字典](拓扑排序)
Posted Harris-H
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[剑指 Offer II 114. 外星文字典](拓扑排序)相关的知识,希望对你有一定的参考价值。
剑指 Offer II 114. 外星文字典(拓扑排序)
先按照相邻单词比较建图。
然后跑拓扑排序。
class Solution
public:
unordered_map<char, vector<char>> edges;
unordered_map<char, int> indegrees;
bool valid = true;
string alienOrder(vector<string>& words)
int length = words.size();
for (auto word : words)
int wordLength = word.size();
for (int j = 0; j < wordLength; j++)
char c = word[j];
if (!edges.count(c))
edges[c] = vector<char>();
for (int i = 1; i < length && valid; i++)
addEdge(words[i - 1], words[i]);
if (!valid)
return "";
queue<char> qu;
for (auto [u, _] : edges)
if (!indegrees.count(u))
qu.emplace(u);
string order;
while (!qu.empty())
char u = qu.front();
qu.pop();
order.push_back(u);
for (char v : edges[u])
indegrees[v]--;
if (indegrees[v] == 0)
qu.emplace(v);
return order.size() == edges.size() ? order : "";
void addEdge(string before, string after)
int length1 = before.size(), length2 = after.size();
int length = min(length1, length2);
int index = 0;
while (index < length)
char c1 = before[index], c2 = after[index];
if (c1 != c2)
edges[c1].emplace_back(c2);
indegrees[c2] += 1;
break;
index++;
if (index == length && length1 > length2)
valid = false;
;
以上是关于[剑指 Offer II 114. 外星文字典](拓扑排序)的主要内容,如果未能解决你的问题,请参考以下文章
Java每日一题——>剑指 Offer II 034. 外星语言是否排序
Java每日一题——>剑指 Offer II 034. 外星语言是否排序