题目描述
现有一种使用字母的全新语言,这门语言的字母顺序与英语顺序不同。您有一个单词列表(从词典中获得的),该单词列表内的单词已经按这门新语言的字母顺序进行了排序。需要根据这个输入的列表,还原出此语言中已知的字母顺序。
示例:
输入:
[
“wrt”,
“wrf”,
“er”,
“ett”,
“rftt”
]输出: “wertf”
解题思路
参考第207和201题,本质还是构建图 + 拓扑排序(入度表 + 队列)。
本题的题意开始没理解好,其实就是给出按照字典序排序好的一堆单词,让你根据这堆单词,找出此语言中已知字母的顺序。所以我们可以得到思路:将词典中字符串的字符两两对比,只有第一个不同的字符才是正确的排序,如ert
和wrf
,只能推断出e
的优先级高于w
(
e
−
>
w
e\ ->\ w
e −> w),剩余字符的优先级不能推断。
所以我们可以先遍历一遍整个单词表,相邻的两个单词两两比较得出一对字符的优先级关系,例如:x -> y
,代表x字符的顺序在y字符前。然后我们将字符串的优先级构建为图,然后进行拓扑排序。如果图中无环,则将拓扑排序输出,否则顺序是非法的。(这其实就是第207和201题的做法了,其实这个题就是多了一步自己找prerequisites
的过程,那两个题已经给出来了。)
class Solution {
private:
int cnt; // 统计出现了的字符数
vector<int> in_degree; //注意,不是26字母都在words中出现,所以入度分为两种情况:没有出现的字母出度为-1,出现了的字母的入度为非负数
vector<vector<int>> graph; // 建图(邻接表的形式)
void init_graph(vector<string>& words) {
for (char c : words[0])
if (in_degree[c - 'a'] == -1) ++cnt,in_degree[c - 'a'] = 0;
for (int i = 0; i < words.size() - 1; i++) {
for (char c : words[i + 1])
if (in_degree[c - 'a'] == -1) ++cnt,in_degree[c - 'a'] = 0;
for (int j = 0; j < words[i].size() && j < words[i+1].size(); j++) {
char from = words[i][j], to = words[i + 1][j];
if (from == to)
continue;
graph[from - 'a'].push_back(to - 'a');
++in_degree[to - 'a'];
break;
}
}
}
string topology_sort() {
string ans = "";
queue<int> q;
for (int i = 0; i < in_degree.size(); i++) {
if (in_degree[i] > 0 || in_degree[i] == -1) continue;
q.push(i);
ans += (i + 'a');
}
while (!q.empty()) {
for (int i = q.size(); i > 0; --i) {
int from = q.front(); q.pop();
for (int to : graph[from]) {
if (in_degree[to] == 1) {
q.push(to);
ans += (to + 'a');
}
--in_degree[to];
}
}
}
return ans.size() == cnt ? ans : "";
}
public:
Solution():cnt(0), in_degree(26, -1), graph(26){
// None
}
string alienOrder(vector<string>& words) {
init_graph(words);
return topology_sort();
}
};
参考代码
见上