Repository navigation
Expand file tree
/
Copy pathP269_Alien_Dictionary.java
More file actions
67 lines (63 loc) · 2.21 KB
/
Copy pathP269_Alien_Dictionary.java
File metadata and controls
67 lines (63 loc) · 2.21 KB
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
package solution.hard;
import java.util.*;
/**
* @author Yi-Lo
* 2021/2/5 10:32
* @version 1.0
* @topics Graph、Topological Sort
* @urllink https://leetcode-cn.com/problems/alien-dictionary/
*/
public class P269_Alien_Dictionary {
public static String alienOrder(String[] words) {
Map<Character, Set<Character>> map = new HashMap<>();
for (int i = 0; i < words.length - 1; i++) {
int currLen = words[i].length(), nextLen = words[i + 1].length();
for (int j = 0; j < currLen && j < nextLen; j++) {
if (words[i].charAt(j) != words[i + 1].charAt(j)) {
Set<Character> set = map.getOrDefault(words[i].charAt(j), new HashSet<>());
set.add(words[i + 1].charAt(j));
map.put(words[i].charAt(j), set);
break;
}
if (currLen > nextLen && j == nextLen - 1) return "";
}
}
int[] degrees = new int[26];
Arrays.fill(degrees, -1);
for (String str : words) {
for (char c : str.toCharArray()) {
degrees[c - 'a'] = 0;
}
}
for (char key : map.keySet()) {
for (char val : map.get(key)) {
degrees[val - 'a']++;
}
}
StringBuilder builder = new StringBuilder();
Queue<Character> queue = new LinkedList<>();
int count = 0;
for (int i = 0; i < 26; i++) {
if (degrees[i] != -1) count++;
if (degrees[i] == 0) {
queue.add((char) ('a' + i));
}
}
while (!queue.isEmpty()) {
Character curr = queue.poll();
builder.append(curr);
if (map.containsKey(curr)) {
Set<Character> set = map.get(curr);
for (Character c : set) {
degrees[c - 'a']--;
if (degrees[c - 'a'] == 0) queue.add(c);
}
}
}
return (builder.length() != count) ? "" : builder.toString();
}
public static void main(String[] args) {
String[] words = {"wrt", "wrf", "er", "ett", "rftt"};
System.out.println(alienOrder(words));
}
}