leetcode 269

问题

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:

1
2
3
4
5
6
7
8
9
10
Input:
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]

Output: "wertf"

Example 2:

1
2
3
4
5
6
7
Input:
[
"z",
"x"
]

Output: "zx"

Example 3:

1
2
3
4
5
6
7
8
9
10
Input:
[
"z",
"x",
"z"
]

Output: ""

Explanation: The order is invalid, so return "".

Note:

  1. You may assume all letters are in lowercase.
  2. You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
  3. If the order is invalid, return an empty string.
  4. There may be multiple valid order of letters, return any one of them is fine.

分析

输入的一系列word,连续的俩俩 word 之间可以确定两个字符之间的先后顺序,或者无法确定得出任意两个字符之间的顺序(前一个字符是后一个字符的前缀的情况下)。因此我们可以使用拓扑排序得到一个符合要求的顺序。另外要注意在所有 word 出现过的字符都要给出在答案中出现,所以先对所有字符遍历一遍将其入度都设置为1表示该字符的存在。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
vector<int> helper(const string &a, const string &b) {
for (int i = 0; i < a.size() && i < b.size(); ++i) {
if (a[i] == b[i]) continue;
return {a[i]-'a', b[i]-'a'};
}
return {};
}

string alienOrder(vector<string>& words) {
vector<int> deg(26, -1);
vector<int> e[26];
for (string &s: words)
for (char &c: s)
deg[c-'a'] = 0;
for (int i = 0; i < words.size()-1; ++i) {
vector<int> a = helper(words[i], words[i+1]);
if (a.size() != 0) {
deg[a[1]]++;
e[a[0]].push_back(a[1]);
}
}

string ans;
queue<int> q;
int totalNum = 0;
for (int i = 0; i < 26; ++i) {
if (deg[i] == 0) q.push(i);
if (deg[i] != -1) totalNum++;
}
while (q.size()) {
int x = q.front();
q.pop();
ans += ('a'+x);
for (int y: e[x]) {
if (--deg[y] == 0) {
q.push(y);
}
}
}
return ans.size() == totalNum? ans: "";
}
};