|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import java.util.Arrays;
|
4 |
| -import java.util.Comparator; |
5 | 4 | import java.util.HashMap;
|
6 | 5 | import java.util.Map;
|
7 | 6 |
|
@@ -29,39 +28,36 @@ public boolean isAlienSorted(String[] words, String order) {
|
29 | 28 |
|
30 | 29 | private boolean sorted(String firstWord, String secondWord, Map<Character, Integer> map) {
|
31 | 30 | for (int i = 0; i < Math.min(firstWord.length(), secondWord.length()); i++) {
|
32 |
| - if (firstWord.charAt(i) == secondWord.charAt(i)) { |
33 |
| - continue; |
34 |
| - } else { |
35 |
| - if (map.get(firstWord.charAt(i)) > map.get(secondWord.charAt(i))) { |
36 |
| - return false; |
37 |
| - } else { |
38 |
| - return true; |
39 |
| - } |
| 31 | + if (firstWord.charAt(i) != secondWord.charAt(i)) { |
| 32 | + return map.get(firstWord.charAt(i)) <= map.get(secondWord.charAt(i)); |
40 | 33 | }
|
41 | 34 | }
|
42 | 35 | return firstWord.length() <= secondWord.length();
|
43 | 36 | }
|
44 | 37 | }
|
45 | 38 |
|
46 | 39 | public static class Solution2 {
|
| 40 | + /** |
| 41 | + * Solution1 above is actually consistently faster than this Solution2 on LeetCode. |
| 42 | + */ |
47 | 43 | public boolean isAlienSorted(String[] words, String order) {
|
48 | 44 | String[] copy = Arrays.copyOf(words, words.length);
|
49 |
| - Arrays.sort(words, new Comparator<String>() { |
50 |
| - @Override |
51 |
| - public int compare(String o1, String o2) { |
52 |
| - int pos1 = 0; |
53 |
| - int pos2 = 0; |
54 |
| - for (int i = 0; i < Math.min(o1.length(), o2.length()) && pos1 == pos2; i++) { |
55 |
| - pos1 = order.indexOf(o1.charAt(i)); |
56 |
| - pos2 = order.indexOf(o2.charAt(i)); |
57 |
| - } |
58 |
| - |
59 |
| - if (pos1 == pos2 && o1.length() != o2.length()) { |
60 |
| - return o1.length() - o2.length(); |
| 45 | + Arrays.sort(words, (o1, o2) -> { |
| 46 | + int pos1 = 0; |
| 47 | + int pos2 = 0; |
| 48 | + for (int i = 0; i < Math.min(o1.length(), o2.length()); i++) { |
| 49 | + pos1 = order.indexOf(o1.charAt(i)); |
| 50 | + pos2 = order.indexOf(o2.charAt(i)); |
| 51 | + if (pos1 != pos2) { |
| 52 | + break; |
61 | 53 | }
|
| 54 | + } |
62 | 55 |
|
63 |
| - return pos1 - pos2; |
| 56 | + if (pos1 == pos2 && o1.length() != o2.length()) { |
| 57 | + return o1.length() - o2.length(); |
64 | 58 | }
|
| 59 | + |
| 60 | + return pos1 - pos2; |
65 | 61 | });
|
66 | 62 | for (int i = 0; i < words.length; i++) {
|
67 | 63 | if (!copy[i].equals(words[i])) {
|
|
0 commit comments