Skip to content

Commit 2fa55dc

Browse files
committed
Update 269_Alien_Dictionary.java
1 parent ca18057 commit 2fa55dc

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed
Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,32 @@
11
class Solution {
22
public String alienOrder(String[] words) {
3-
Map<Character, List<Character>> adjList = new HashMap<>();
4-
Map<Character, Integer> inorderMap = new HashMap<>();
3+
if (words == null || words.length == 0) {
4+
return "";
5+
}
6+
7+
Map<Character, List<Character>> graph = new HashMap<>();
8+
Map<Character, Integer> inorder = new HashMap<>();
59

6-
for (String word : words) {
7-
for (char c : word.toCharArray()) {
8-
adjList.putIfAbsent(c, new ArrayList<>());
9-
inorderMap.putIfAbsent(c, 0);
10+
for (String w : words) {
11+
for (char c : w.toCharArray()) {
12+
graph.putIfAbsent(c, new ArrayList<>());
13+
inorder.putIfAbsent(c, 0);
1014
}
1115
}
1216

1317
for (int i = 0; i < words.length - 1; i++) {
14-
String word1 = words[i];
15-
String word2 = words[i + 1];
18+
String word1 = words[i], word2 = words[i + 1];
1619

1720
if (word1.length() > word2.length() && word1.startsWith(word2)) {
1821
return "";
1922
}
2023

2124
for (int j = 0; j < Math.min(word1.length(), word2.length()); j++) {
22-
if (word1.charAt(j) != word2.charAt(j)) {
23-
adjList.get(word1.charAt(j)).add(word2.charAt(j));
24-
inorderMap.put(word2.charAt(j), inorderMap.get(word2.charAt(j)) + 1);
25+
char c1 = word1.charAt(j), c2 = word2.charAt(j);
26+
27+
if (c1 != c2) {
28+
graph.get(c1).add(c2);
29+
inorder.put(c2, inorder.get(c2) + 1);
2530
break;
2631
}
2732
}
@@ -30,8 +35,8 @@ public String alienOrder(String[] words) {
3035
Queue<Character> q = new LinkedList<>();
3136
StringBuilder sb = new StringBuilder();
3237

33-
for (char c : inorderMap.keySet()) {
34-
if (inorderMap.get(c) == 0) {
38+
for (Character c : inorder.keySet()) {
39+
if (inorder.get(c) == 0) {
3540
q.offer(c);
3641
}
3742
}
@@ -40,17 +45,19 @@ public String alienOrder(String[] words) {
4045
char c = q.poll();
4146
sb.append(c);
4247

43-
for (char neighbour : adjList.get(c)) {
44-
inorderMap.put(neighbour, inorderMap.get(neighbour) - 1);
45-
if (inorderMap.get(neighbour) == 0) {
48+
for (char neighbour : graph.get(c)) {
49+
inorder.put(neighbour, inorder.get(neighbour) - 1);
50+
51+
if (inorder.get(neighbour) == 0) {
4652
q.offer(neighbour);
4753
}
4854
}
4955
}
5056

51-
if (sb.length() < inorderMap.size()) {
57+
if (sb.length() < inorder.size()) {
5258
return "";
5359
}
60+
;
5461
return sb.toString();
5562
}
5663
}

0 commit comments

Comments
 (0)