269 Alien Dictionary

1. Question

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: Given the following words in dictionary,
1
[
2
"wrt",
3
"wrf",
4
"er",
5
"ett",
6
"rftt"
7
]
Copied!
The correct order is:"wertf".
Example 2: Given the following words in dictionary,
1
[
2
"z",
3
"x"
4
]
Copied!
The correct order is:"zx".
Example 3: Given the following words in dictionary,
1
[
2
"z",
3
"x",
4
"z"
5
]
Copied!
The order is invalid, so return"".
Note:
  1. 1.
    You may assume all letters are in lowercase.
  2. 2.
    You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.
  3. 3.
    If the order is invalid, return an empty string.
  4. 4.
    There may be multiple valid order of letters, return any one of them is fine.

2. Implementation

(1) BFS
1
class Solution {
2
public String alienOrder(String[] words) {
3
if (words == null || words.length == 0) {
4
return "";
5
}
6
7
Map<Character, Integer> inDegree = new HashMap<>();
8
Map<Character, Set<Character>> adjList = new HashMap<>();
9
10
11
for (String word : words) {
12
for (char c : word.toCharArray()) {
13
inDegree.put(c, 0);
14
}
15
}
16
17
for (int i = 0; i < words.length - 1; i++) {
18
String curWord = words[i];
19
String nextWord = words[i + 1];
20
21
for (int j = 0; j < Math.min(curWord.length(), nextWord.length()); j++) {
22
char c1 = curWord.charAt(j);
23
char c2 = nextWord.charAt(j);
24
25
// We can only know the lexicographical order from the first two different words
26
if (c1 != c2) {
27
Set<Character> set = adjList.getOrDefault(c1, new HashSet<>());
28
29
if (!set.contains(c2)) {
30
set.add(c2);
31
adjList.put(c1, set);
32
inDegree.put(c2, inDegree.get(c2) + 1);
33
}
34
break;
35
}
36
// This is not lexicographically order
37
else if (j + 1 < curWord.length() && j + 1 == nextWord.length()) {
38
return "";
39
}
40
}
41
}
42
43
Queue<Character> queue = new LinkedList<>();
44
for (char key: inDegree.keySet()) {
45
if (inDegree.get(key) == 0) {
46
queue.add(key);
47
}
48
}
49
50
51
StringBuilder res = new StringBuilder();
52
53
while (!queue.isEmpty()) {
54
char curC = queue.remove();
55
res.append(curC);
56
57
if (adjList.containsKey(curC)) {
58
for (char nextC : adjList.get(curC)) {
59
inDegree.put(nextC, inDegree.get(nextC) - 1);
60
61
if (inDegree.get(nextC) == 0) {
62
queue.add(nextC);
63
}
64
}
65
}
66
}
67
return res.length() == inDegree.size() ? res.toString() : "";
68
}
69
}
Copied!

3. Time & Space Complexity

BFS:时间复杂度O(n * L), n为word的个数,L为每个word的平均长度, 空间复杂度O(k), k为不同的character个数