#Problem

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

#Solution

Topological sort经典题了. 不用多解释了. 做不出来自己面壁.

#Code

#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
class Solution {
public String alienOrder(String[] words) {
final Map<Character, Set<Character>> graph = new HashMap<>();
final int n = words.length;
for (int i = 0; i < n - 1; i++) {
final String w1 = words[i];
final String w2 = words[i + 1];
for (int k = 0; k < Math.max(w1.length(), w2.length()); k++) {
if (k < w1.length()) graph.putIfAbsent(w1.charAt(k), new HashSet<>());
if (k < w2.length()) graph.putIfAbsent(w2.charAt(k), new HashSet<>());
}
for (int k = 0; k < Math.min(w1.length(), w2.length()); k++) {
if (w1.charAt(k) != w2.charAt(k)) {
graph.get(w1.charAt(k)).add(w2.charAt(k));
break;
}
}
}
for (int k = 0; k < words[n - 1].length(); k++) {
graph.putIfAbsent(words[n - 1].charAt(k), new HashSet<>());
}
final Stack<Character> stack = new Stack<>();
final int[] visited = new int[26];
for (final char v : graph.keySet()) {
if (visited[v - 'a'] == 0) {
if (!topoSort(v, graph, visited, stack)) {
return "";
}
}
}
final StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.toString();
}
private boolean topoSort(final char v, final Map<Character, Set<Character>> graph, final int[] visited, final Stack<Character> stack) {
if (visited[v - 'a'] == -1) return false;
if (visited[v - 'a'] == 1) return true;
visited[v - 'a'] = -1;
for (final char adj : graph.get(v)) {
if (!topoSort(adj, graph, visited, stack)) {
return false;
}
}
visited[v - 'a'] = 1;
stack.push(v);
return true;
}
}

Comments