Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 21, 2018 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/b420ead243f35c53411b4fa849454d3a to your computer and use it in GitHub Desktop.
Save jianminchen/b420ead243f35c53411b4fa849454d3a to your computer and use it in GitHub Desktop.
Leetcode 269 - Alien dictionary
/*
Leetcode 269: Alien dictionary
http://www.cnblogs.com/grandyang/p/5250200.html
Study the algorithm on 7/21/2018 3:01 PM
这道题让给了我们一些按“字母顺序”排列的单词,但是这个字母顺序不是我们熟知的顺序,而是另类的顺序,让我们根据这些“有序”的单词
来找出新的字母顺序,这实际上是一道有向图的问题,跟之前的那两道Course Schedule II和Course Schedule的解法很类似,我们先来
看BFS的解法,我们需要一个set来保存我们可以推测出来的顺序关系,比如题目中给的例子,我们可以推出的顺序关系有:
t->f
w->e
r->t
e->r
那么set就用来保存这些pair,我们还需要另一个set来保存所有出现过的字母,需要一个一维数组in来保存每个字母的入度,另外还要一个
queue来辅助拓扑遍历,我们先遍历单词集,把所有字母先存入ch,然后我们每两个相邻的单词比较,找出顺序pair,然后我们根据这些pair
来赋度,我们把ch中入度为0的字母都排入queue中,然后开始遍历,如果字母在set中存在,则将其pair中对应的字母的入度减1,若此时入度
减为0了,则将对应的字母排入queue中并且加入结果res中,直到遍历完成,我们看结果res和ch中的元素个数是否相同,若不相同则说明可能
有环存在,返回空字符串,参见代码如下:
*/
class Solution {
public:
string alienOrder(vector<string>& words) {
set<pair<char, char> > s;
unordered_set<char> ch;
vector<int> in(256, 0);
queue<char> q;
string res = "";
for (auto a : words) ch.insert(a.begin(), a.end());
for (int i = 0; i < words.size() - 1; ++i) {
int mn = min(words[i].size(), words[i + 1].size()), j = 0;
for (; j < min(words[i].size(), words[i + 1].size()); ++j) {
if (words[i][j] != words[i + 1][j]) {
s.insert(make_pair(words[i][j], words[i + 1][j]));
break;
}
}
if (j == mn && words[i].size() > words[i + 1].size()) return "";
}
for (auto a : s) ++in[a.second];
for (auto a : ch) {
if (in[a] == 0) {
q.push(a);
res += a;
}
}
while (!q.empty()) {
char c = q.front(); q.pop();
for (auto a : s) {
if (a.first == c) {
--in[a.second];
if (in[a.second] == 0) {
q.push(a.second);
res += a.second;
}
}
}
}
return res.size() == ch.size() ? res : "";
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment