-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathAlien Dictionary.java
48 lines (47 loc) · 1.65 KB
/
Alien Dictionary.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
class Solution {
public String alienOrder(String[] words) {
Map<Character, Set<Character>> graph = new HashMap<>();
for (String word : words) {
for (char c : word.toCharArray()) {
graph.computeIfAbsent(c, k -> new HashSet<>());
}
}
for (int i = 0; i < words.length - 1; i++) {
String word1 = words[i];
String word2 = words[i + 1];
int minLength = Math.min(word1.length(), word2.length());
if (word1.length() > word2.length() && word1.startsWith(word2)) {
return "";
}
for (int j = 0; j < minLength; j++) {
if (word1.charAt(j) != word2.charAt(j)) {
graph.get(word1.charAt(j)).add(word2.charAt(j));
break;
}
}
}
StringBuilder sb = new StringBuilder();
Map<Character, Boolean> visited = new HashMap<>();
for (Character c : graph.keySet()) {
if (dfs(c, graph, sb, visited)) {
return "";
}
}
return sb.reverse().toString();
}
private boolean dfs(Character c, Map<Character, Set<Character>> graph,
StringBuilder sb, Map<Character, Boolean> visited) {
if (visited.containsKey(c)) {
return visited.get(c);
}
visited.put(c, true);
for (Character neighbor : graph.getOrDefault(c, new HashSet<>())) {
if (dfs(neighbor, graph, sb, visited)) {
return true;
}
}
visited.put(c, false);
sb.append(c);
return false;
}
}