269. Alien Dictionary
There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
Example 1:
Input:
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
Output: "wertf"
Example 2:
Input:
[
"z",
"x"
]
Output: "zx"
Example 3:
Input:
[
"z",
"x",
"z"
]
Output: ""
Explanation: The order is invalid, so return "".
Note:
- You may assume all letters are in lowercase.
- You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
- If the order is invalid, return an empty string.
- There may be multiple valid order of letters, return any one of them is fine.
方法1: topological sort
思路:
这道题注意单词内部的字母不隐含order,也就是说从第一个次来看,w, r, t之间没有顺序。只有单词和单词之间包含着order的信息。所以我们要两两对比连续的单词,找到第一个不一样的字母,将所有这样的instance放进图里。注意如果是”er”, “err”,可以提前在较短的单词结束时结束对比,这样的pair无法给graph贡献任何信息。图建好后用course schedule II的方式排序。直到遍历完成,我们看结果res和ch中的元素个数是否相同,若不相同则说明可能有环存在,返回空字符串。
用到的数据结构:
unordered_map<char, int> indegree;
unordered_map<char, unordered_set<\char>> graph;
易错点
- 较短单词结束时提前结束
- 遇到第一个不一样的字符时,impose一下字母序,如果之前没有见过的话,indegree累加,但只要见过不一样的,都要记得break:后面的字母不一样也没有任何影响。
- if (set.find(next[j]) == set.end()), 避免重复增加indegree
- 最后检查res大小。
Complexity
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
string alienOrder(vector<string>& words) {
if (words.size() == 0) return "";
unordered_map<char, int> indegree;
unordered_map<char, unordered_set<char>> graph;
//initialize
for (int i = 0; i < words.size(); i++) {
for (int j = 0; j < words[i].size(); j ++) {
char c = words[i][j];
indegree[c] = 0;
}
}
// build graph and indegree
for (int i = 0; i < words.size() - 1; i ++) {
string cur = words[i];
string next = words[i + 1];
int mn = min(cur.size(), next.size());
for (int j = 0; j < mn; j++) {
if (cur[j] != next[j]) {
unordered_set<char> set = graph[cur[j]];
if (set.find(next[j]) == set.end()){
graph[cur[j]].insert(next[j]);
indegree[next[j]]++;
}
break;
}
}
}
// generate topological sort
string result;
queue<char> q;
// initialize
for (auto & e : indegree) {
if (e.second == 0) {
q.push(e.first);
}
}
// sort
while (!q.empty()) {
char top = q.front();
q.pop();
result += top;
for (auto next: graph[top]) {
indegree[next]--;
if (indegree[next] == 0) {
q.push(next);
}
}
}
// tell if it is cyclic
return result.length() == indegree.size() ? result : "";
}
};