|
1 | 1 | class Solution {
|
2 | 2 | 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++); |
6 | 7 | }
|
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)) { |
9 | 10 | return false;
|
10 | 11 | }
|
11 | 12 | }
|
12 | 13 | return true;
|
13 | 14 | }
|
14 | 15 |
|
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) { |
22 | 20 | return false;
|
23 |
| - } |
24 |
| - if (dictionaryDiff < 0) { |
25 |
| - correctOrder = true; |
26 |
| - break; |
| 21 | + } else if (diff < 0) { |
| 22 | + return true; |
27 | 23 | }
|
28 | 24 | }
|
29 |
| - return correctOrder || firstWord.length() <= secondWord.length(); |
| 25 | + return wordOne.length() <= wordTwo.length(); |
30 | 26 | }
|
31 | 27 | }
|
0 commit comments