Skip to content

Commit 13fc282

Browse files
authored
Update Verifying an Alien Dictionary.java
1 parent c5acea2 commit 13fc282

File tree

1 file changed

+13
-17
lines changed

1 file changed

+13
-17
lines changed
Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,27 @@
11
class Solution {
22
public boolean isAlienSorted(String[] words, String order) {
3-
Map<Character, Integer> dictionary = new HashMap<>();
4-
for (int i = 0; i < order.length(); i++) {
5-
dictionary.put(order.charAt(i), i);
3+
Map<Character, Integer> map = new HashMap<>();
4+
int idx = 0;
5+
for (char c : order.toCharArray()) {
6+
map.put(c, idx++);
67
}
7-
for (int i = 0; i < words.length - 1; i++) {
8-
if (!hasCorrectOrder(words[i], words[i + 1], dictionary)) {
8+
for (int i = 1; i < words.length; i++) {
9+
if (!isSorted(words[i - 1], words[i], map)) {
910
return false;
1011
}
1112
}
1213
return true;
1314
}
1415

15-
private boolean hasCorrectOrder(String firstWord, String secondWord, Map<Character, Integer> dictionary) {
16-
int idxOne = 0;
17-
int idxTwo = 0;
18-
boolean correctOrder = false;
19-
while (idxOne < firstWord.length() && idxTwo < secondWord.length()) {
20-
int dictionaryDiff = dictionary.get(firstWord.charAt(idxOne++)) - dictionary.get(secondWord.charAt(idxTwo++));
21-
if (dictionaryDiff > 0) {
16+
private boolean isSorted(String wordOne, String wordTwo, Map<Character, Integer> map) {
17+
for (int i = 0; i < Math.min(wordOne.length(), wordTwo.length()); i++) {
18+
int diff = map.get(wordOne.charAt(i)) - map.get(wordTwo.charAt(i));
19+
if (diff > 0) {
2220
return false;
23-
}
24-
if (dictionaryDiff < 0) {
25-
correctOrder = true;
26-
break;
21+
} else if (diff < 0) {
22+
return true;
2723
}
2824
}
29-
return correctOrder || firstWord.length() <= secondWord.length();
25+
return wordOne.length() <= wordTwo.length();
3026
}
3127
}

0 commit comments

Comments
 (0)