-
Notifications
You must be signed in to change notification settings - Fork 16
/
AlienDictionary.java
68 lines (62 loc) · 2.21 KB
/
AlienDictionary.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// https://leetcode.com/problems/alien-dictionary
// C = length of all words added together
// T: O(C)
// S: O(1)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public class AlienDictionary {
public String alienOrder(String[] words) {
// Step 0: Create data structures and find all unique letters.
Map<Character, List<Character>> adjList = new HashMap<>();
Map<Character, Integer> counts = new HashMap<>();
for (String word : words) {
for (char c : word.toCharArray()) {
counts.put(c, 0);
adjList.put(c, new ArrayList<>());
}
}
// Step 1: Find all edges.
for (int i = 0; i < words.length - 1; i++) {
String word1 = words[i];
String word2 = words[i + 1];
// Check that word2 is not a prefix of word1.
if (word1.length() > word2.length() && word1.startsWith(word2)) {
return "";
}
// Find the first non match and insert the corresponding relation.
for (int j = 0; j < Math.min(word1.length(), word2.length()); j++) {
if (word1.charAt(j) != word2.charAt(j)) {
adjList.get(word1.charAt(j)).add(word2.charAt(j));
counts.put(word2.charAt(j), counts.get(word2.charAt(j)) + 1);
break;
}
}
}
// Step 2: Breadth-first search.
StringBuilder sb = new StringBuilder();
Queue<Character> queue = new LinkedList<>();
for (Character c : counts.keySet()) {
if (counts.get(c).equals(0)) {
queue.add(c);
}
}
while (!queue.isEmpty()) {
Character c = queue.remove();
sb.append(c);
for (Character next : adjList.get(c)) {
counts.put(next, counts.get(next) - 1);
if (counts.get(next).equals(0)) {
queue.add(next);
}
}
}
if (sb.length() < counts.size()) {
return "";
}
return sb.toString();
}
}